public class Test implements Comparable<Test>{ private Integer stu_id; private Integer stu_age; public Student(Integer stu_id,Integer stu_age){ this.stu_id = stu_id; this.stu_age = stu_age; } public Student(){ }
@Override public int compareTo(Test o) { return this.stu_age - o.stu_age; } }
public class Test { public static void main(String[] args) { int[] arrays = new int[]{1, 4, 6, 2, 8}; quick(arrays, 0, arrays.length - 1); System.out.println(Arrays.toString(arrays)); }
public static void quick(int[] arr, int startIndex, int endIndex) { // 基准条件检查,避免递归栈溢出 if (startIndex >= endIndex) { return; } // 获取分区点 int pIndex = partition(arr, startIndex, endIndex); // 递归排序左子数组 quick(arr, startIndex, pIndex - 1); // 递归排序右子数组 quick(arr, pIndex + 1, endIndex); }
public static int partition(int[] arr, int startIndex, int endIndex) { int pivot = arr[startIndex]; // 选择第一个元素作为基准 int left = startIndex; // 左指针 int right = endIndex; // 右指针
while (left < right) { // 从右向左找到第一个小于pivot的元素 while (left < right && arr[right] >= pivot) { right--; } // 从左向右找到第一个大于pivot的元素 while (left < right && arr[left] <= pivot) { left++; } // 交换左右指针所指的元素 if (left < right) { int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } }