java排序算法系列(二)——快速排序
测试代码:
Java代码
package com.zlpy.quicksort;
public class MainClass {
/**
* @param args
*/
public static void main(String[] args) {
int[] r={48,62,35,77,43,55,14,98,24};
//排序前输出
QuickSort.print(r);
sort(r,0,r.length-1);
//排序后输出
QuickSort.print(r);
}
public static void sort(int[] r,int left,int right){
if(left<right){
int pos = QuickSort.quickSort(r, left, right);
sort(r, left, pos-1);
sort(r,pos+1,right);
}
}
}
算法代码:
Java代码
package com.zlpy.quicksort;
public class QuickSort {
/*一趟快速排序的算法*/
public static int quickSort(int[] r,int left,int right){
int low=left;
int high=right;
int x=r[low];
while(low<high){
while(low<high && x<r[high]){
high--;
}
if(low<high){
r[low]=r[high];
low++;
}
while(low<high && x>r[low]){
low++;
}
if(low<high){
r[high]=r[low];
high--;
}
}
r[low]=x;
return low;
}
public static void print(int[] r){
String str = "";
for(int i=0;i<r.length;i++){
str+=r[i]+" ";
}
System.out.println(str);
}
}
作者“幻刈紫真 至简大道”
补充:软件开发 , Java ,