1.快速排序
@Test public void test() { int[] nums = {10, 7, 2, 4, 7, 62, 3, 4, 2, 1, 8, 9, 19}; quickSort(nums, 0, nums.length - 1); for (int num : nums) System.out.println(num); }
private void quickSort(int[] nums, int low, int high) {
if (low >= high) return; int l = low, r = high; int pivot = nums[low]; while (l < r) { while (l < r && nums[r] > pivot) r--; while (l < r && nums[l] <= pivot) l++; if (l < r) { int t = nums[l]; nums[l] = nums[r]; nums[r] = t; } } nums[low] = nums[l]; nums[l] = pivot; quickSort(nums, low, r - 1); quickSort(nums, r + 1, high); }
|
2.归并排序
public class Merge_Sort { @Test public void test() { int[] nums = {10, 7, 2, 4, 7, 62, 3, 4, 2, 1, 8, 9, 19}; mergeSort(nums); System.out.println(Arrays.toString(nums)); }
private void mergeSort(int[] nums) { if (nums == null || nums.length <= 1) return; int[] tmp = new int[nums.length]; mergeSort(nums, 0, nums.length - 1, tmp); }
private void mergeSort(int[] nums, int l, int r, int[] tmp) { if (l == r) return; int mid = l + (r - l) / 2; mergeSort(nums, l, mid, tmp); mergeSort(nums, mid + 1, r, tmp); merge(nums, l, mid, r, tmp); }
private void merge(int[] nums, int l, int mid, int r, int[] tmp) { int idx = l; int i = l, j = mid + 1; while (i <= mid && j <= r) { if (nums[i] <= nums[j]) { tmp[idx++] = nums[i++]; } else { tmp[idx++] = nums[j++]; } } while (i <= mid) tmp[idx++] = nums[i++]; while (j <= r) tmp[idx++] = nums[j++]; System.arraycopy(tmp, l, nums, l, r - l + 1); }
|
3.堆排序
堆是具有以下性质的完全二叉树:每个结点的值都大于或等于其左右孩子结点的值,称为大顶堆;
或者每个结点的值都小于或等于其左右孩子结点的值,称为小顶堆。如下图:
参考资料:堆排序(超详细图解 java版)
主要步骤:
1.将无序序列构建成一个堆,根据升序降序需求选择大顶堆或小顶堆(升序一般用大顶堆)
2.将堆顶元素与末尾元素交换,将最大元素"沉"到数组末端
3.重新调整结构,使其满足堆定义,然后继续交换堆顶元素与当前末尾元素
4.反复执行调整+交换步骤,直到整个序列有序
public class Heap { @Test public void test() { int[] nums = {4, 5, 6, 3, 2, 1}; HeapSort(nums); System.out.println(Arrays.toString(nums)); }
private void HeapSort(int[] nums) { int len = nums.length; for (int i = len / 2 - 1; i >= 0; i--) { sink(nums, i, len - 1); } for (int i = len - 1; i >= 1; i--) { swap(nums, 0, i); sink(nums, 0, i - 1); } }
private void sink(int[] nums, int target, int end) { int idx = target; while (2 * idx + 1 <= end) { int maxLR = 2 * idx + 1; if (maxLR + 1 <= end && nums[maxLR + 1] > nums[maxLR]) { maxLR++; } if (nums[idx] < nums[maxLR]) { swap(nums, idx, maxLR); } else { break; } idx = maxLR; } }
private void swap(int[] nums, int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } }
|