Javacollections已经内置了一些常用算法,此处作为标记,方便温故而知新
1、二分查找
public class BinarySearch {
public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T data) {
int start = 0;
int end = list.size() - 1;
while (start <= end) {
int mid = (end + start) >>> 1;
Comparable<? super T> midVal = list.get(mid);
if (midVal.compareTo(data) == 0) {
return mid;
} else if (midVal.compareTo(data) > 0) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
}
public static void main(String[] args) {
int i = binarySearch(Arrays.asList(1, 2, 3, 6, 8, 44, 99, 145), 18);
System.out.println(i);
}
}
2、斐波拉契数列(Fibonacci),除第一个和第二个数外,任意一个数都可由前两个数相加得到
public class FibonacciDemo {
public static ArrayList<Integer> fib(int size) {
int a = 0;
int b = 1;
//中间结果标记
int n = 0;
//数组长度计数器
int len = 0;
ArrayList<Integer> nums = new ArrayList<>();
while (len <= size) {
len++;
n = a + b;
nums.add(n);
a = b;
b = n;
}
return nums;
}
public static void main(String[] args) {
ArrayList<Integer> fibList = fib(10);
System.out.println(fibList);
}
}