ADV-297 快速排序 java
2024-10-08 13:53:10
问题描述
用递归来实现快速排序(quick sort)算法。快速排序算法的基本思路是:假设要对一个数组a进行排序,且a[0] = x。首先对数组中的元素进行调整,使x放在正确的位置上。同时,所有比x小的数都位于它的左边,所有比x大的数都位于它的右边。然后对于左、右两段区域,递归地调用快速排序算法来进行排序。
输入格式:输入只有一行,包括若干个整数(不超过10个),以0结尾。
输出格式:输出只有一行,即排序以后的结果(不包括末尾的0)。
输入输出样例
用递归来实现快速排序(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
import java.util.*; public class Main { // static void swap(int a, int b) { //交换的另外一种方式
// a = a ^ b;
// b = a ^ b;
// a = a ^ b;
// } static void quicksort(int[] a, int i, int j) {
if(i >= j)return;
int x = 0;
int temp = a[i];
int low = i;
int high = j; while(low < high) {
while(a[high] >= temp && low < high) high--;
while(a[low] <= temp && low < high) low++;
if(low < high) {
x = a[low];
a[low] = a[high];
a[high] = x;
}
}
a[i] = a[high];
a[high] = temp; quicksort(a, i, high-1);
quicksort(a, high+1, j);
} public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int[] c = new int[11];
int sign = 1;
int index = 0;
while(true) {
sign = sc.nextInt();
if(sign == 0) break;
c[index++] = sign;
}
int[] b = new int[index];
b = Arrays.copyOfRange(c, 0, index); quicksort(b, 0, b.length-1);
for(int i = 0; i < b.length; i++)
System.out.print(b[i] + " ");
}
}
重新认识了一些细节,仅记录。
最新文章
- Max double slice sum 的解法
- maven编译报错 -source 1.5 中不支持 lambda 表达式
- 02、AngularJs的数据绑定
- HDU5724 Chess(SG定理)
- BZOJ3276 : 磁力
- 转:MIME(Multipurpose Internet Mail Extensions)类型
- bug_ _ android.view.WindowManager$BadTokenException: Unable to add window -- token
- CSS3 动画记
- iOS常见面试题汇总
- Kruskal(克鲁斯卡尔)
- B - 瑶瑶带你玩激光坦克
- 在ie下,a标签包被img的时候,为什么有个蓝色的边线
- MySQL访问控制实现原理
- ABAP中的枚举对象
- 【简单理解】gulp和webpack的区别
- 版本控制——TortoiseSVN (1)安装与配置
- Java中的List转换成JSON报错(五)
- select2 下拉搜索控件
- MyBatis Generator 自定义生成注释
- 关于c++的一篇随笔
热门文章
- 5_3 安迪的第一个字典(UVa10815)<;set的使用>;
- kibana 开发工具介绍
- Uncaught SyntaxError: Unexpected identifier 报错 import Vue from &#39;vue&#39;;
- fastJson javaBean和JSON对象相互转换
- 影响IPSec的网络问题
- mqtt.mini.js 使用
- AngularJS学习:第一个demo
- 【转】shell处理mysql增删改查
- SpringBoot学习笔记(一)——构建springboot项目
- security.web.firewall.RequestRejectedException: The request was rejected because the URL contained a potentially malicious String ";;";