package demo;
import java.util.Arrays;
/**
* User: ldj
* Date: 2024/6/4
* Time: 13:18
* Description: No Description
*/
public class MathDemo {
public static void main(String[] args) {
int[] array = new int[]{3, 1, 5, 2, 4};
buboSort(array);
System.out.println(Arrays.toString(array));
}
//冒泡算法
public static void buboSort(int[] array) {
for (int i = 1; i <= array.length - 1; i++) {
for (int j = 0; j < array.length - i; j++) {
int temp = 0;
if (array[j] > array[j + 1]) {
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
//二分法查找
public static int binarySearch(int[] arr, int value) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (value == arr[mid]) {
return mid;
}
if (value > arr[mid]) {
low = mid + 1;
}
if (value < arr[mid]) {
high = mid - 1;
}
}
//没有找到返回-1
return -1;
}
//斐波那契数列 1、1、2、3、5、8、13
public static int fibonacci(int n) {
if (n == 1 || n == 2) {
return 1;
}
//当前第n个数等于该数的前两个数之和
if (n > 2) {
return fibonacci(n - 1) + fibonacci(n - 2);
}
return -1;
}
public static long fibonacci2(int n) {
if (n < 1) {
return -1;
}
if (n == 1 || n == 2) {
return 1;
}
long a = 1L, b = 1L, c = 0L;
for (int i = 0; i < n - 2; i++) {
c = a + b; //第3个数的值等于前两个数的和
a = b; //第2个数的值赋值给第1个数
b = c; //第3个数的值赋值给第2个数
}
return c;
}
}
冒泡,二分查找,斐波那契数列
最新推荐文章于 2024-10-30 18:07:32 发布