快速排序
基本思想:选一个数作为基准,用这个数将数组中的每个数都做一遍对比
以从小到大的排序为例:要求基准数的左边数均不大于它,右边的数均不小于它
这样就会得到以基准数为区分的左右两个区间,再对两个区间进行排序即可
/**
* 快速排序
* 基本思想:选一个数作为基准,用这个数将数组中的每个数都做一遍对比
* 以从小到大的排序为例:要求基准数的左边数均不大于它,右边的数均不小于它
* 这样就会得到以基准数为区分的左右两个区间,再对两个区间进行排序即可
*/
package test;
import java.util.Scanner;
public class quicksort {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int a[] = new int [10];
for(int i = 0;i < 10;i++) {
a[i] = sc.nextInt();
}
quick(a,0,a.length - 1);
for(int i = 0;i < a.length;i++) {
System.out.print(a[i] + " ");
}
}
public static void quick(int a[],int low,int high) {
int temp,p;
if (low > high) return;
p = a[low];//方便起见,每次将第一个作为基准,后面比它小的放到它左边,比它大的放到右边
int i = low;
int j = high;
while(i < j) {//重合时结束第一次循环
while(a[j] >= p && i < j) {//右边开始,j向左移动
j--;
}
while(a[i] <= p && i < j) {//左边开始,i向右移动
i++;
}
if(i < j) {//满足条件时a[i],a[j]交换
temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
//将基准(刚开始的第一个数)放到i标签和j标签重合时的位置
a[low] = a[i];
a[i] = p;
//分别递归调用基准左边的和右边的数组
quick(a,i + 1,high);
quick(a,low,i - 1);
}
}