public class FastSort{
public static void main(String []args){
System.out.println("Hello World");
int[] a = {12,20,5,16,15,1,30,45,23,9};
int start = 0;
int end = a.length-1;
sort(a,start,end);
for (int i = 0; i<a.length; i++){
System.out.println(a[i]);
}
}
public void sort(int[] a,int low,int high){
int start = low;
int end = high;
int key = a[low];
while(end>start){
//从后往前比较
while(end>start&&a[end]>=key) //如果没有比关键值小的,比较下一个,直到有比关键值小的交换位置,然后又从前往后比较
end--;
if(a[end]<=key){
int temp = a[end];
a[end] = a[start];
a[start] = temp;
}
//从前往后比较
while(end>start&&a[start]<=key)//如果没有比关键值大的,比较下一个,直到有比关键值大的交换位置
start++;
if(a[start]>=key){
int temp = a[start];
a[start] = a[end];
a[end] = temp;
}
//此时第一次循环比较结束,关键值的位置已经确定了。左边的值都比关键值小,右边的值都比关键值大,但是两边的顺序还有可能是不一样的,进行下面的递归调用
}
//递归
if(start>low) sort(a,low,start-1);
//左边序列。第一个索引位置到关键值索引-1
if(end<high) sort(a,end+1,high);
//右边序列。从关键值索引+1到最后一个
}
}
/**
* 功能描述: 快速排序,双向扫描
*
* @date 2017-09-12 10:17
* @since V1.0.0
*/
public class QuickSort {
public static void main(String[] args){
Integer[] arr = {8, 2, 9, 1, 5, 10, 12, 3, 18, 6};
System.out.println(Arrays.asList(arr));
quickSort(arr, 0, arr.length - 1);
System.out.println(Arrays.asList(arr));
}
public static void quickSort(Integer[] arr, int left, int right) {
if(left < right) {
int partition = partition(arr, left, right);
quickSort(arr, left, partition - 1);
quickSort(arr, partition + 1, right);
}
}
public static int partition(Integer[] arr, int left, int right) {
Integer pivot = arr[left];
int i = left, j = right;
while (i < j) {
while (arr[j] >= pivot && i < j) {
j--;
}
arr[i] = arr[j];
while (arr[i] <= pivot && i < j) {
i++;
}
arr[j] = arr[i];
}
arr[i] = pivot;
return i;
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有