Java实现快速排序
先上代码,贴到IDE中就能看到结果
package sort;
public class QuickSort {
public static void main(String[] args) {
int[] arry = {5,7,9,1,4,6};
mySort(arry,0,arry.length-1);
for(int i = 0;i<arry.length;i++) {
System.out.println(arry[i]);
}
}
//排序方法
private static void mySort(int[] arry,int low ,int high) {
int i = low;
int j = high;
int tmp = arry[low];
while(i!=j) {
while(arry[j]>=tmp&&i<j) {
j--;
}
while(arry[i]<=tmp&&i<j) {
i++;
}
swapArry(arry,i,j);
}
swapArry(arry,i,low);
if(low<i-1) {
mySort(arry,low,i-1);
}
if(i+1<high) {
mySort(arry,i+1,high);
}
}
//交换数组中的元素
private static void swapArry(int[] arry,int i,int j) {
int tmp = arry[i];
arry[i] = arry[j];
arry[j] = tmp;
}
}
代码解析:
尝试用语言表述逻辑失败,灵魂画手上线,结合代码应该能看明白