二分法查找:
package chapter1;
import java.util.Arrays;
public class BinarySearch {
private static int[] source = {3, 9, 5, 2, 7 ,3, 6};
private static int key = 7;
private static int Search(int[] a, int mid) {
int length = a.length;
if (a[mid] == key) {
return a[mid];
} else if (a[mid] > key) {
mid = (length - mid) / 2;
return Search(a, mid);
} else if (a[mid] < key) {
mid = (length - mid) / 2 + mid;
return Search(a, mid);
}
return -1;
}
public static void main(String[] args) {
Arrays.sort(BinarySearch.source);
int result = Search(BinarySearch.source, BinarySearch.source.length / 2);
System.out.print(result);
}
}
归并排序:
package chapter2;
/**
* Created by Blue on 2017/6/3.
*/
public class Merge {
private static Comparable[] aux;
public static void sort(Comparable[] a) {
aux = new Comparable[a.length];
sort(a, 0, a.length - 1);
}
private static void sort(Comparable[] a, int lo, int hi) {
if (hi <= lo) {
return;
}
int mid = lo + (hi - lo) / 2;
sort(a, lo, mid);
sort(a, mid + 1, hi);
merge(a, lo, mid, hi);
}
private static void merge(Comparable[] a, int lo, int mid, int hi) {
int i = lo, j = mid + 1;
for (int k = lo; k <= hi; k++) {
aux[k] = a[k];
}
for (int k = lo; k <= hi; k++) {
if (i > mid) {
a[k] = aux[j++];
} else if (j > hi) {
a[k] = aux[i++];
} else if (less(aux[j], aux[i])) {
a[k] = aux[j++];
} else {
a[k] = aux[i++];
}
}
}
public static boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
}
public static void exch(Comparable[] a, int i, int j) {
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
}
public static boolean isSorted(Comparable[] a) {
for (int i = 1; i < a.length; i++) {
if (less(a[i], a[i - 1])) {
return false;
}
}
return true;
}
public static void show(Comparable[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
String[] a = {"80", "30", "60", "40", "20", "10", "50", "70"};
sort(a);
assert isSorted(a);
show(a);
}
}