要点
1.快速排序
public static void quickSort(int[] arr, int left, int right) {
if (left < right) {
int p = partition(arr, left, right);
quickSort(arr, 0, p);
quickSort(arr, p + 1, right);
}
}
/**
* 来回倒腾
* @param arr
* @param low
* @param high
* @return
*/
private static int partition(int[] arr, int low, int high) {
int left = low;
int right = high;
int target = arr[low];
while (left < right) {
while (arr[right] > =target && right > left) {
right--;
}
int temp=arr[left];
arr[left]=arr[right];
while (arr[left] < target && left < right) {
left++;
}
arr[right]=temp;
}
arr[left]=target;
return left;
}
2.归并排序
public static void mergeSort(int[] arr) {
sort(arr, 2, 5);
}
public static void sort(int[] arr, int low, int high) {
if (low < high) {
int mid = (low + high) / 2;
sort(arr, low, mid);
sort(arr, mid + 1, high);
// 左右归并
merge(arr, low, mid, high);
}
}
public static void merge(int[] arr, int left, int mid, int right) {
int[] tmp = new int[right-left+1];// 辅助数组
int p1 = left, p2 = mid + 1, k = left;// p1、p2是检测指针,k是存放指针
while (p1 <= mid && p2 <= right) {
if (arr[p1] <= arr[p2]) {
tmp[k++] = arr[p1++];
} else {
tmp[k++] = arr[p2++];
}
}
while (p1 <= mid) {
tmp[k++] = arr[p1++];// 如果第一个序列未检测完,直接将后面所有元素加到合并的序列中
}
while (p2 <= right) {
tmp[k++] = arr[p2++];// 同上
}
// 复制回原素组
for (int i = 0; i <= tmp.length; i++) {
arr[left+i] = tmp[i];
}
}
网友评论