具体讲解:快速排序
import java.util.Arrays;
/**
* @Author: wangshiyu javapub rodert
* @Date: 2021/3/28 15:04
*/
public class MyQuickSort {
public static void main(String[] agrs) {
MyQuickSort myQuickSort = new MyQuickSort();
int[] arr = {3, 1, 5, 2, 4};
myQuickSort.quickSort(arr, 0, arr.length - 1);
for (int i : arr
) {
System.out.println(i);
}
}
public int[] quickSort(int[] arr, int left, int right) {
System.out.println(Arrays.toString(arr));
if (left < right) {
int partitionIndex = partition(arr, left, right);
quickSort(arr, left, partitionIndex - 1);
quickSort(arr, partitionIndex + 1, right);
}
return arr;
}
public int partition(int[] arr, int left, int right) {
// 设定基准值(pivot)
int pivot = left;
int index = pivot + 1;
for (int i = index; i <= right; i++) {
if (arr[i] < arr[pivot]) {
swap(arr, i, index);
index++;
}
}
swap(arr, pivot, index - 1);
return index - 1;
}
public void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}