Version #2 Generate a random number between start and end and use it as the pivot
public class Solution {
/**
* @param A an integer array
* @return void
*/
public void sortIntegers2(int[] A) {
// Write your code here
if (A == null || A.length <= 1) return;
quickSort(A, 0, A.length - 1);
}
private static void quickSort(int[] A, int start, int end) {
if (start >= end) return;
int mid = partition(A, start, end);
quickSort(A, start, mid - 1);
quickSort(A, mid, end);
}
//return the index of left pointer
private static int partition(int[] A, int start, int end) {
int left = start, right = end;
Random rd = new Random();
int pivot = A[start + rd.nextInt(end - start + 1)];
while (left <= right) {
while (A[left] < pivot) left++;
while (A[right] > pivot) right--;
if (left <= right) {
swap(A, left, right);
left++;
right--;
}
}
return left;
}
private static void swap(int[] A, int left, int right) {
int temp = A[left];
A[left] = A[right];
A[right] = temp;
}
}
Version#1 Using the mid position as the pivot
public class Solution {
/**
* @param A an integer array
* @return void
*/
//Quick Sort
public void sortIntegers(int[] A) {
// Write your code here
if (A == null || A.length == 0) {
return;
}
quickSort(A, 0, A.length - 1);
}
public void quickSort(int[] A, int start, int end) {
if (start >= end) {
return;
}
int left = start;
int right = end;
int pivot = A[(start + end) / 2];
while(left <= right) {
while (left <= right && A[left] < pivot) {
left++;
}
while (left <= right && A[right] > pivot) {
right--;
}
if (left <= right) {
int temp = A[left];
A[left] = A[right];
A[right] = temp;
left++;
right--;
}
}
quickSort(A, start, right);
quickSort(A, left, end);
}
}
No comments:
Post a Comment