当前位置: 代码迷 >> 综合 >> 手写快速排序算法——QuickSort(Java代码实现)
  详细解决方案

手写快速排序算法——QuickSort(Java代码实现)

热度:95   发布时间:2023-09-27 12:15:50.0

QuickSort

/*** @program: JavaTest* @description: 快速排序实现* @author: yanghaoran* @create: 2019-05-26 12:17**/
public class QuickSort {static int[] a = {4, 5, 7, 1, 9, 8, 3, 2, 6};// 结果集数组int[] result = new int[a.length];public static void main(String[] args) {QuickSort qS = new QuickSort();qS.result = qS.quickSort(a);// 遍历展示for (int i = 0; i < qS.result.length; i++) {System.out.print(qS.result[i] + " ");}}public int[] quickSort (int[] b) {// 左指针int left = 0;// 右指针int right = b.length - 2;// 自我选定预轴心(几乎可以随意选择看自己数组内容恰当选择)int pivot = b.length - 1;// 左指针右移for (int i = 1; b[left] <= b[pivot] && i <= b.length - 1; i++) {left = i;}// 右指针左移for (int i = b.length - 1; b[right] >= b[pivot] && i >= 0; i--) {right = i;}// 左右指针相撞找到目标轴心if (left == right || left == right + 1) {int temp = b[left];b[left] = b[pivot];b[pivot] = temp;// 以轴心为轴分割为两个数组int[] tempArray1 = new int[left];int[] tempArray2 = new int[b.length - right - 2];for (int i = 0; i < left; i++) {tempArray1[i] = b[i];}for (int i = 0; i < right - 1; i++) {tempArray2[i] = b[i + left + 1];}// 递归结束条件(长度1或者2都为结束因为顺序会被排好)if (tempArray1.length == 1 || tempArray1.length == 2) {return tempArray1;} else {tempArray1 = quickSort(tempArray1);// 递归出来后对原数组进行恢复for (int i = 0; i < left; i++) {b[i] = tempArray1[i];}}// 递归结束条件(长度1或者2都为结束因为顺序会被排好)if (tempArray2.length == 1 || tempArray2.length == 2) {return tempArray2;} else {tempArray2 = quickSort(tempArray2);// 递归出来后对原数组进行恢复for (int i = 0; i < right - 1; i++) {b[i + left + 1] = tempArray2[i];}}// 左右指针未相撞,交换左右指针内容继续递归左右指针的平移} else {int temp = b[left];b[left] = b[right];b[right] = temp;quickSort(b);}return b;}
}

自己因为之前对快速排序长时间不用就已经忘记了,特意重新写了一遍追加记忆,如有不明白即可交流~
**如果对快速排序原理有疑问可以先看视频~**https://www.bilibili.com/video/av39093184?t=199
也可评论交流其他排序算法~

  相关解决方案