快速排序代码
非普通快速排序,根据二维数组的第0位值对二维数组排序。
一维数组的排序只要相应修改就可以。
public class QuickSort {
public void quicksort(int[][] array){
quicksort(array, 0, array.length-1);
}
public void quicksort(int[][] array, int left, int right){
int pivotIndex = (left+right)/2;
int[] pivot = array[pivotIndex];
if(left<0 || right<0 || left >= right){
return;
}
if(right - left == 1){
if(array[left][0] > array[right][0]){
swap(array, left, right);
}else{
return;
}
}
int index = partition(array, left, right, pivot);
quicksort(array, left, index-1);
quicksort(array, index, right);
}
public int partition(int[][] array, int left, int right, int[] pivot){
while(left < right){
while(array[left][0] < pivot[0]){
left++;
}
while(array[right][0] > pivot[0]){
right--;
}
if(left < right){
swap(array, left, right);
left++;
right--;
}
}
if(left == right){
if(array[left][0] <= pivot[0]){
return left+1;
}else{
return left;
}
}
return Math.max(left,right);
}
public void swap(int[][] array, int left, int right){
int[] temp;
temp = array[left];
array[left] = array[right];
array[right] = temp;
}
}