前面我详细讲解了快排算法,现在我们用java来实现
直接上代码
package ttt;
public class kuaisupaixu {
public static int[] quickSort(int[] the_array,int start,int end) {
if (start<=end) {
int m = start;
int n = end;
int the_base = the_array[m];
while (m<n) {
while((m<n)&&(the_array[n]>=the_base)) {
n--;
}
the_array[m]=the_array[n];
while((m<n)&&(the_array[m]<=the_base)){
m++;
}
the_array[n]=the_array[m];
the_array[m]=the_base;
quickSort(the_array,start,m-1);
quickSort(the_array,n+1,end);
}
}
return the_array;
}
public static void main(String[] args) {
int []the_array = {10,1,18,30,23,12,7,5,18,17};
System.out.print("之前的排序:");
for(int i = 0; i < the_array.length; i++) {
System.out.print(the_array[i] + " ");
}
int []result_array = quickSort(the_array,0,the_array.length-1);
System.out.print("快速排序:");
for(int i = 0; i < result_array.length; i++) {
System.out.print(result_array[i] + " ");
}
}
}
运行结果如下
之前的排序:10 1 18 30 23 12 7 5 18 17 快速排序:1 5 7 10 12 17 18 18 23 30