privatevoidquickSort(int[] nums, int left, int right){ if (left >= right) { return; } int pivot = portion(nums, left, right); quickSort(nums, left, pivot); quickSort(nums, pivot + 1, right); }
// 分配并返回基准点 pivot privateintportion(int[] nums, int left, int right){ int pivot = left; // 待交换的元素 int index = left + 1; for (int i = index; i <= right; i++) { if (nums[i] < nums[pivot]) { swap(nums, i, index); index ++; } } // 将基准值与最后一个小于基准值的元素进行交换 swap(nums, pivot, index - 1); return index - 1; }
privatevoidswap(int[] nums, int i, int j){ int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; }
publicvoidsort(int[] nums){ int len = nums.length;
// find min and max int min = nums[0], max = nums[0]; for (int i = 1; i < len; i ++) { if (nums[i] < min) { min = nums[i]; } elseif (nums[i] > max) { max = nums[i]; } }
// statistics int cLen = max - min + 1; int[] bucket = newint[cLen]; for (int n : nums) { bucket[n - min] ++; }
// fill // 待填充的索引,从0开始 int index = 0; for (int i = 0; i < cLen; i ++) { // 从小到大,逐个将bucket的索引即nums的值填入nums中 while (bucket[i] > 0) { nums[index] = i + min; bucket[i] --; index ++; } } }
publicvoidsort(int[] nums, int bucketSize){ // 构建桶数组 int[][] buckets = newint[bucketSize][0]; int min = nums[0], max = nums[0]; for (int i = 1; i < nums.length; i ++) { if (nums[i] < min) { min = nums[i]; } elseif (nums[i] > max) { max = nums[i]; } } int bucketSpan = (max - min) / bucketSize + 1; for (int val : nums) { int index = (val - min) / bucketSpan; buckets[index] = arrAppend(buckets[index], val); } // 排序 int index = 0; for (int[] bucket : buckets) { // 桶内排序 if (bucket.length == 0) { continue; } Arrays.sort(bucket); for (int b : bucket) { nums[index] = b; index ++; } } }
publicvoidsort(int[] arr){ int len = arr.length; // 构建最大堆 buildMaxHeap(arr, len); // n * log(n) // 排序 最大索引的无序节点与根节点交换值 n * log(n) for (int i = len - 1; i > 0; i --) { swap(arr, 0, i); len --; heapify(arr, 0, len); } }
privatevoidbuildMaxHeap(int[] arr, int len){ // 从倒数第二层节点开始向下处理 for (int i = len / 2; i >= 0; i --) { heapify(arr, i, len); } }
privatevoidheapify(int[] arr, int i, int len){ int left = 2 * i + 1; int right = 2 * i + 2; int largest = i; if (left < len && arr[left] > arr[largest]) { largest = left; } if (right < len && arr[right] > arr[largest]) { largest = right; } if (largest != i) { swap(arr, i, largest); // 由于larget(left or right)的值改变了,所以需要向下遍历 heapify(arr, largest, len); } }
privatevoidswap(int[] arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }