0. 排序
- 常用的排序有快速排序、归并排序、堆排序。
- 下面列出各个排序所包含的方法,便于记忆。
1. 快速排序
- sort(int[] arr)
- sort(int[] arr, int left, int right)
2. 归并排序
- sort(int[] arr)
- sort(int[] arr, int left, int right)
- merge(int[] arr, int left, int mid, int right)
3. 堆排序
- sort(int[] arr)
- adjust(int[] arr, int i, int len)
- swap(int[] arr, int i, int j)
4. 代码
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] arr1 = new int[]{3, 1, 5, 7, 2, 4, 9, 6, 0, 8, 5, 6};
QuickSort.sort(arr1);
print(arr1);
int[] arr2 = new int[]{3, 1, 5, 7, 2, 4, 9, 6, 0, 8, 5, 6};
MergeSort.sort(arr2);
print(arr2);
int[] arr3 = new int[]{3, 1, 5, 7, 2, 4, 9, 6, 0, 8, 5, 6};
HeapSort.sort(arr3);
print(arr3);
}
public static void print(int[] arr) {
for (int i : arr) {
System.out.print(i + "\t");
}
System.out.println();
}
}
class QuickSort {
public static void sort(int[] arr) {
int n = arr.length;
sort(arr, 0, n - 1);
}
public static void sort(int[] arr, int left, int right) {
if (left < right) {
int low = left;
int high = right;
int pivot = arr[low];
while (low < high) {
while (low < high && arr[high] >= pivot) {
high--;
}
arr[low] = arr[high];
while (low < high && arr[low] <= pivot) {
low++;
}
arr[high] = arr[low];
}
arr[low] = pivot;
sort(arr, left, low - 1);
sort(arr, low + 1, right);
}
}
}
class MergeSort {
public static void sort(int[] arr) {
int n = arr.length;
sort(arr, 0, n - 1);
}
public static void sort(int[] arr, int left, int right) {
if (left < right) {
int mid = left + ((right - left) >> 1);
sort(arr, left, mid);
sort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
public static void merge(int[] arr, int left, int mid, int right) {
int[] leftArr = Arrays.copyOfRange(arr, left, mid + 1);
int[] rightArr = Arrays.copyOfRange(arr, mid + 1, right + 1);
int n1 = leftArr.length;
int n2 = rightArr.length;
int i = 0;
int j = 0;
int k = left;
while (i < n1 && j < n2) {
arr[k++] = leftArr[i] < rightArr[j] ? leftArr[i++] : rightArr[j++];
}
while (i < n1) {
arr[k++] = leftArr[i++];
}
while (j < n2) {
arr[k++] = rightArr[j++];
}
}
}
class HeapSort {
public static void sort(int[] arr) {
int n = arr.length;
for (int i = (n >> 1) - 1; i >= 0; i--) {
adjust(arr, i, n);
}
for (int i = n - 1; i > 0; i--) {
swap(arr, 0, i);
adjust(arr, 0, i);
}
}
public static void adjust(int[] arr, int i, int len) {
for (int k = i * 2 + 1; k < len; k = k * 2 + 1) {
if (k + 1 < len && arr[k + 1] > arr[k]) {
k++;
}
if (arr[k] > arr[i]) {
swap(arr, i, k);
i = k;
} else {
break;
}
}
}
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}