classSolution { privatevoidmerge(int[] a, int[] aux, int lo, int mid, int hi) { // copy to aux[] for (intk= lo; k <= hi; k++) { aux[k] = a[k]; }
// merge back to a[] inti= lo, j = mid + 1; for (intk= lo; k <= hi; k++) { if (i > mid) a[k] = aux[j++]; elseif (j > hi) a[k] = aux[i++]; elseif (aux[j] < aux[i]) a[k] = aux[j++]; else a[k] = aux[i++]; } }
publicint[] sortArray(int[] nums) { finalintN= nums.length; int[] aux = newint[N]; for (intlen=1; len < N; len *= 2) { for (intlo=0; lo < N - len; lo += len + len) { intmid= lo + len - 1; inthi= Math.min(lo + len + len - 1, N - 1); merge(nums, aux, lo, mid, hi); } } return nums; } }
Submission Detail
11 / 11 test cases passed.
Runtime: 7 ms, faster than 34.85% of Java online submissions for Sort an Array.
Memory Usage: 46.7 MB, less than 12.67% of Java online submissions for Sort an Array.
classSolution { privatevoidexch(int[] a, int i, int j) { intswap= a[i]; a[i] = a[j]; a[j] = swap; }
privatevoidsort(int[] a, int lo, int hi) { if (hi <= lo) return; intlt= lo, gt = hi; intv= a[lo]; inti= lo + 1; while (i <= gt) { if (a[i] < v) exch(a, lt++, i++); elseif (a[i] > v) exch(a, i, gt--); else i++; }
Heapsort breaks into two phases: heap construction, where we reorganize the original array into a heap, and the sortdown, where we pull the items out of the heap in decreasing order to build the sorted result.
Q. Why not use a[0] in the heap representation?
A. Doing so simplifies the arithmetic a bit. It is not difficult to implement the heap methods based on a 0-based heap where the children of a[0] are a[1] and a[2], the children of a[1] are a[3] and a[4], the children of a[2] are a[5] and a[6], and so forth, but most programmers prefer the simpler arithmetic that we use. Also, using a[0] as a sentinel value (in the parent of a[1]) is useful in some heap applications.
classSolution { privatevoidexch(int[] a, int i, int j) { intswap= a[i]; a[i] = a[j]; a[j] = swap; }
privatevoidsink(int[] pq, int k, int n) { intlargest= k; intl=2 * k + 1; intr=2 * k + 2; if (l < n && pq[l] > pq[largest]) largest = l; if (r < n && pq[r] > pq[largest]) largest = r; if (largest != k) { exch(pq, k, largest); sink(pq, largest, n); } }
publicint[] sortArray(int[] nums) { intn= nums.length; for (intk= n / 2 - 1; k >= 0; k--) sink(nums, k, n); for (intk= n - 1; k > 0; k--) { exch(nums, 0, k); sink(nums, 0, k); } return nums; } }
Submission Detail
11 / 11 test cases passed.
Runtime: 7 ms, faster than 30.29% of Java online submissions for Sort an Array.
Memory Usage: 46.7 MB, less than 32.93% of Java online submissions for Sort an Array.