Given an array of integers nums, sort the array in ascending order.
public int[] mergeSort(int[] nums) {
mergeSort(nums, 0, nums.length-1);
return nums;
}
public void mergeSort(int[] nums, int start, int end) {
if(start >= end) return;
int mid = start + (end - start) / 2;
mergeSort(nums, start, mid);
mergeSort(nums, mid+1, end);
int[] temp = new int[end - start + 1];
int p = start, q = mid+1, i = 0;
while(p <= mid && q <= end)
temp[i++] = nums[p] < nums[q] ? nums[p++] : nums[q++];
while(p <= mid) temp[i++] = nums[p++];
while(q <= end) temp[i++] = nums[q++];
System.arraycopy(temp, 0, nums, start, end - start + 1);
}
public void quickSort(int[] nums, int start, int end) {
if(start >= end) return;
int l = start + 1, r = end;
while(l <= r) {
if(nums[l] > nums[start])
swap(nums, l--, r--);
l++;
}
l--;
swap(nums, l, start);
quickSort(nums, start, l-1);
quickSort(nums, l+1, end);
}
public int[] heapSort(int[] nums) {
for(int i = nums.length-1; i >= 0; i--) {
maxHeapify(nums, i, nums.length-1);
}
System.out.println(Arrays.toString(nums));
int end = nums.length-1;
while(end >= 0) {
swap(nums, 0, end--);
for(int i = 0; i <= end; i++) {
maxHeapify(nums, i, end);
}
}
return nums;
}
public void maxHeapify(int[] nums, int i, int limit) {
int l = 2 * i + 1, r = 2 * i + 2;
int maxIndex = i;
if(l <= limit) maxIndex = nums[l] > nums[maxIndex] ? l : maxIndex;
if(r <= limit) maxIndex = nums[r] > nums[maxIndex] ? r : maxIndex;
if(maxIndex != i) {
swap(nums, i, maxIndex);
maxHeapify(nums, maxIndex, limit);
}
}