1、排序
(1)冒泡排序:
例:
public void bubbleSort(Integer[] arr, int n) {
if (n <= 1) return;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n - i - 1; ++j) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
(2)选择排序
例:
public static int[] sort(int[] ins){
int n = ins.length-1;
for(int i=0; i<n; i++){
int min_index = i;
for(int j=i+1; j<n; j++){
if(ins[j]<ins[i]){
min_index = j;
}
}
if(min_index != i){
int temp = ins[i];
ins[i] = ins[min_index];
ins[min_index] = temp;
}
}
return ins;
}
2、二分查找
源码:
private static int binarySearch(int[] a, int fromIndex, int toIndex, int key) {
int low = fromIndex;
int high = toIndex - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
int midVal = a[mid];
if (midVal < key)
low = mid + 1;
else if (midVal > key)
high = mid - 1;
else
return mid;
}
return -(low + 1);
}
3、Arrays:针对数组进行操作的工具类,比如说排序和查找。
public static String toString(int[] a):把数组转成字符串
public static void sort(int[] a):对数组进行排序
public static in binarySearch(int[] a, int key):二分查找