面试题有一道快速排序的
自己不懂 就查了查 有个写的真心不错 https://blog.csdn.net/Yexiaofen/article/details/78018204
先看看原理 自己写写代码 明白每步为什么这么些 之后在自己脑子里过两边 就欧克啦
首先解释以下说明是快速排序:
package com.xystedu.demo;
import java.util.Arrays;
public class QuickSort {
public static void main(String[] args) {
int[] a = {8, 2, 4, 5, 7, 4, 5 ,3 ,9 ,0};
System.out.println(Arrays.toString(a));
quickSort(a);
System.out.println(Arrays.toString(a));
}
public static void quickSort(int[] a) { //防止数组为空
if(a.length>0) {
quickSort(a, 0 , a.length-1);
}
}
private static void quickSort(int[] a, int low, int high) {
//1,找到递归算法的出口
if( low > high) {
return;
}
//2, 存
int i = low; //从右往左第一个小于key的下标数
System.out.println("low +"+ low);
int j = high; //从左往右找到第一个大于key的下标数
System.out.println("high +"+ high);
//3,key
int key = a[ low ];
System.out.println(key);
//4,完成一趟排序
while( i< j) {
//4.1 ,从右往左找到第一个小于key的数
while(i<j && a[j] > key){
j--;
}
// 4.2 从左往右找到第一个大于key的数
while( i<j && a[i] <= key) {
i++;
}
//System.out.println("i= "+i );
//System.out.println("j= "+j );
//4.3 交换
if(i<j) {
int p = a[i];
a[i] = a[j];
a[j] = p;
System.out.println(Arrays.toString(a));
}
}
// 4.4,调整key的位置
// System.out.println("i= "+i );
//System.out.println("j= "+j );
int p = a[i];
a[i] = a[low];
a[low] = p;
System.out.println(Arrays.toString(a));
//5, 对key左边的数快排
quickSort(a, low, i-1 ); //
//6, 对key右边的数快排
quickSort(a, i+1, high);
}
}
本来想写点注释 但实在没什么好写的
如有侵权 ,前联系我删除!