快速排序(递归版)
java
import java.util.Arrays;
public class QuickSort {
public static void sort(int[] arr, int low, int high) {
if (arr == null || arr.length == 0)
return;
if (low >= high)
return;
// pick the pivot
int middle = low + (high - low) / 2;
int pivot = arr[middle];
// make left < pivot and right > pivot
int i = low, j = high;
while (i <= j) {
while (arr[i] < pivot) {
i++;
}
while (arr[j] > pivot) {
j--;
}
if (i <= j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
// recursively sort two sub parts
if (low < j)
sort(arr, low, j);
if (high > i)
sort(arr, i, high);
}
public static void main(String[] args) {
int[] arr = { 3, 7, 8, 5, 2, 1, 9, 5, 4 };
QuickSort.sort(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
}二分查找
java
public class BinarySearch {
public static int search(int[] arr, int target) {
if (arr == null || arr.length == 0)
return -1;
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int target = 5;
System.out.println(BinarySearch.search(arr, target));
}
}

