class Solution {
public int[] sortArray(int[] nums) {
if (nums == null || nums.length <= 1) {
return nums;
}
quickSort(nums, 0, nums.length - 1);
return nums;
}
private void quickSort(int[] nums, int start, int end) {
if (start >= end) {
// no need to sort
return;
}
// step 1: select a pivot
Random rand = new Random();
int randPivot = rand.nextInt(end - start + 1);
int pivotLocation = start + randPivot;
int pivot = nums[pivotLocation];
// step 2: partition
swap(nums, pivotLocation, end);
int left = start;
int right = end - 1;
while (left <= right) {
while (left <= right && nums[left] <= pivot) {
left++;
}
while (left <= right && nums[right] >= pivot) {
right--;
}
if (left < right) {
swap(nums, left, right);
}
}
swap(nums, left, end);
quickSort(nums, start, left - 1);
quickSort(nums, left + 1, end);
return;
}
public void swap(int[] nums, int index1, int index2) {
int temp = nums[index1];
nums[index1] = nums[index2];
nums[index2] = temp;
}
}