Given an array of integers, sort the elements in the array in ascending order. The quick sort algorithm should be used to solve this problem.
Examples
- {1} is sorted to {1}
- {1, 2, 3} is sorted to {1, 2, 3}
- {3, 2, 1} is sorted to {1, 2, 3}
- {4, 2, -3, 6, 1} is sorted to {-3, 1, 2, 4, 6}
Corner Cases
- What if the given array is null? In this case, we do not need to do anything.
- What if the given array is of length zero? In this case, we do not need to do anything.
public class Solution {
Random rand = new Random();
public int[] quickSort(int[] array) {
//base case
if (array == null || array.length == 1) {
return array;
}
quickSort(array, 0, array.length - 1);
return array;
}
public void quickSort(int[] array, int left, int right) {
//base case
if(left >= right) {
return;
}
//randomly select an element
int pivotIndex = left + rand.nextInt(right - left + 1);
swap(array, pivotIndex, right);
//partition logic
int i = 0;
int j = right - 1;
while(i <= j) {
if(array[i] > array[right]) {
swap(array, i, j);
j--;
} else {
i++;
}
}
swap(array, i, right);
//subproblem
quickSort(array, left, i-1);
quickSort(array, i+1, right);
}
private void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
方法二:思路和方法一一样,但是把partition部分抽出来单独写成了一个method,if判断部分方法二写得更详细(但更不好理解),按方法一写即可。另外,random部分两种写法略有区别。
public class Solution {
public int[] quickSort(int[] array) {
//base case
if(array == null) {
return array;
}
quickSort(array, 0, array.length - 1);
return array;
}
public void quickSort(int[] array, int left, int right) {
//base case
if(left >= right) {
return;
}
//define a pivot and use the pivot to partiton the arrya
int pivotPost = partition(array, left, right);
//subproblem
quickSort(array, left, pivotPost - 1);
quickSort(array, pivotPost + 1, right);
}
private int partition(int[] array, int left, int right){
int pivotIndex = pivotIndex(left, right);
int pivot = array[pivotIndex];
swap(array, pivotIndex, right);
int leftBound = left;
int rightBound = right - 1;
while(leftBound <= rightBound) {
if(array[leftBound] < pivot) {
leftBound++;
} else if (array[rightBound] >= pivot) {
rightBound--;
} else {
swap(array, leftBound++, rightBound--);
}
}
swap(array, leftBound, right);
return leftBound;
}
private int pivotIndex(int left, int right) {
return left + (int)(Math.random() * (right - left + 1));
}
private void swap(int[] array, int left, int right) {
int temp = array[left];
array[left] = array[right];
array[right] = temp;
}
}