题目:
试题 算法提高 快速排序
资源限制
时间限制:1.0s 内存限制:256.0MB
问题描述
用递归来实现快速排序(quick sort)算法。快速排序算法的基本思路是:假设要对一个数组a进行排序,且a[0] = x。首先对数组中的元素进行调整,使x放在正确的位置上。同时,所有比x小的数都位于它的左边,所有比x大的数都位于它的右边。然后对于左、右两段区域,递归地调用快速排序算法来进行排序。
输入格式:输入只有一行,包括若干个整数(不超过10个),以0结尾。
输出格式:输出只有一行,即排序以后的结果(不包括末尾的0)。
输入输出样例
样例输入
5 2 6 1 7 3 4 0
样例输出
1 2 3 4 5 6 7
解题思路:这道题说到底就是一道快速排序,快速排序的思想可参考这篇文章快速排序
package 蓝桥练习;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int a[] = new int[10];
//索引的下标值
int index = 0;
Scanner s = new Scanner(System.in);
for(int i=0;i<a.length;i++) {
int x = s.nextInt();
if(x==0) {
break;
}
a[i] = x;
index++;
}
quickSort(a,0,index-1);
//排序后输出
for(int i=0;i<index;i++) {
System.out.print(a[i]+" ");
}
s.close();
}
//快速排序
public static void quickSort(int[] a,int low,int high) {
if(low<high) {
//获取正确的索引值
int index = getIndex(a,low,high);
//递归遍历左半部分和右半部分
quickSort(a, 0, index-1);
quickSort(a, index+1, high);
}
}
//获取正确的索引值
public static int getIndex(int[] a,int low,int high) {
//基准数据
int temp = a[low];
while(low<high) {
//先从后半部分检索,比基准数据大的,high--
while(low<high && a[high]>=temp) {
high--;
}
//找到比基准值小的
a[low] = a[high];
//再从前半部分开始检索,比基准数据小的,low++
while(low<high && a[low]<=temp) {
low++;
}
//找到比基准值大的
a[high] = a[low];
}
//循环结束后low=high,这个位置就是基准值的位置(小的在左边,大的在右边)
a[low] = temp;
//返回基准数据的正确下标
return low;
}
}