import java.util.Scanner;
public class QuicklySort {
/**
* 快速排序算法
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
int n = sc.nextInt();
int[] numbers = new int[n];
for (int i=0;i<n;i++){
numbers[i] = sc.nextInt();
}
quick(numbers);
printArr(numbers);
}
}
public static int getMiddle(int[] numbers,int low,int high){
int temp = numbers[low]; //数组第一个作为中轴
while (low < high){
while(low < high && numbers[high] > temp){
high--;
}
numbers[low] = numbers[high]; //比中轴小的移动到低端
while(low < high && numbers[low] < temp){
low++;
}
numbers[high] = numbers[low]; //比中轴大的移动到高端
}
numbers[low] = temp; //中轴记录到尾
return low; //返回中轴位置
}
public static void quickSort(int[] numbers,int low,int high){
if (low <high){
int middle = getMiddle(numbers,low,high); //将numbers数组进行一分为二
quickSort(numbers,low,middle-1); //对低字段表进行递归排序
quickSort(numbers,middle+1,high); //对高字段表进行递归排序
}
}
public static void quick(int[] numbers){
if (numbers.length>0){ //查看数组是否为空
quickSort(numbers,0,numbers.length-1);
}
}
public static void printArr(int[] numbers){
for(int i=0;i<numbers.length;i++){
System.out.print(numbers[i]+",");
}
}
}
快速排序算法小结
最新推荐文章于 2022-04-01 20:43:28 发布