快速排序的实现细节,你真的懂了?
互联网侦察
共 1778字,需浏览 4分钟
·
2021-11-10 00:18
前言
框架
public static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static int innerFindPivot(int[] arr, int start, int end) {
// TODO
}
public static void innerQuickSort(int[] arr, int start, int end) {
int pivot = innerFindPivot(arr, start, end);
if(start < pivot - 1) {
innerQuickSort(arr, start, pivot - 1);
}
if(pivot + 1 < end) {
innerQuickSort(arr, pivot + 1, end);
}
}
public static void quickSort(int[] arr) {
innerQuickSort(arr, 0, arr.length - 1);
}
三种方式
public static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static int innerFindPivot(int[] arr, int start, int end) {
int left = start, right = end;
int pivot = arr[start];
while(left < right) {
while(left < right && arr[right] > pivot) {
right--;
}
while(left < right && arr[left] <= pivot) {
left++;
}
if(left < right) {
swap(arr, left, right);
}
}
swap(arr, start, left);
return left;
}
public static void innerQuickSort(int[] arr, int start, int end) {
int pivot = innerFindPivot(arr, start, end);
if(start < pivot - 1) {
innerQuickSort(arr, start, pivot - 1);
}
if(pivot + 1 < end) {
innerQuickSort(arr, pivot + 1, end);
}
}
public static void quickSort(int[] arr) {
innerQuickSort(arr, 0, arr.length - 1);
}
public static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static int innerFindPivot(int[] arr, int start, int end) {
int left = start, right = end;
boolean isLeft = true;
while(left < right) {
if(arr[left] <= arr[right]) {
if(isLeft) {
left++;
} else {
right--;
}
} else {
swap(arr, left, right);
isLeft = !isLeft;
}
}
return left;
}
public static void innerQuickSort(int[] arr, int start, int end) {
int pivot = innerFindPivot(arr, start, end);
if(start < pivot - 1) {
innerQuickSort(arr, start, pivot - 1);
}
if(pivot + 1 < end) {
innerQuickSort(arr, pivot + 1, end);
}
}
public static void quickSort(int[] arr) {
innerQuickSort(arr, 0, arr.length - 1);
}
public static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public static int innerFindPivot(int[] arr, int start, int end) {
int mark = start;
int pivot = arr[start];
for(int i = start + 1; i <= end; i++) {
if(arr[i] < pivot) {
mark++;
swap(arr, mark, i);
}
}
swap(arr, start, mark);
return mark;
}
public static void innerQuickSort(int[] arr, int start, int end) {
int pivot = innerFindPivot(arr, start, end);
if(start < pivot - 1) {
innerQuickSort(arr, start, pivot - 1);
}
if(pivot + 1 < end) {
innerQuickSort(arr, pivot + 1, end);
}
}
public static void quickSort(int[] arr) {
innerQuickSort(arr, 0, arr.length - 1);
}
练习题
评论