标签:
快速排序(Quick Sort)的基本思想是,通过一趟排序将待排记录分割成独立的两部分,其中一部分记录的关键字均比另一部分记录的关键字小,则可对这两部分记录继续进行排序,以达到整个序列有序的目的。
package Sort;
public class QuickSort {
private void Qsort(int[] list, int low, int high){
int privot;
if(low < high) {
print(list);
/*算出枢轴值privot*/
privot = Partition(list, low, high);
/*对低子表递归排序*/
Qsort(list, low, privot-1);
/*对高子表递归排序*/
Qsort(list, privot+1, high);
}
}
private int Partition(int[] list, int low, int high){
/*用表的第一个记录做枢轴记录*/
int privotkey = list[low];
while (low < high){
while (low < high && list[high] > privotkey)
high--;
/*将比枢轴记录小的记录交换到低端*/
swap(list, low, high);
while (low < high && list[low] < privotkey)
low++;
/*将比枢轴记录大的记录交换到高端*/
swap(list, low, high);
}
/*返回枢轴所在的位置*/
return low;
}
private void swap(int [] list,int j, int i){
int temp;
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
private void print(int[] data) {
System.out.println("当前list数组的值:");
for (int i = 0; i < data.length; i++) {
System.out.print(data[i] + "\t");
}
System.out.println();
}
public static void main(String[] args) {
int[] list = {50,40,80,30,60,70,10,90,20};
QuickSort qs = new QuickSort();
qs.Qsort(list, 0, list.length-1);
qs.print(list);
}
}
private void Qsort(int[] list, int low, int high){
int privot;
if(low < high) {
print(list);
/*算出枢轴值privot*/
privot = Partition(list, low, high);
/*对低子表递归排序*/
Qsort(list, low, privot-1);
/*对高子表递归排序*/
Qsort(list, privot+1, high);
}
}
private int Partition(int[] list, int low, int high){
/*用表的第一个记录做枢轴记录*/
int privotkey = list[low];
while (low < high){
while (low < high && list[high] > privotkey)
high--;
/*将比枢轴记录小的记录交换到低端*/
swap(list, low, high);
while (low < high && list[low] < privotkey)
low++;
/*将比枢轴记录大的记录交换到高端*/
swap(list, low, high);
}
/*返回枢轴所在的位置*/
return low;
}
当前list数组的值: 50 40 80 30 60 70 10 90 20 当前list数组的值: 20 40 10 30 50 70 60 90 80 当前list数组的值: 10 20 40 30 50 70 60 90 80 当前list数组的值: 10 20 30 40 50 70 60 90 80 当前list数组的值: 10 20 30 40 50 60 70 90 80 当前list数组的值: 10 20 30 40 50 60 70 80 90
最优情况下,快速排序算法的时间复杂度为O(nlogn),空间复杂度也为O(nlogn)
标签:
原文地址:http://www.cnblogs.com/danbing/p/5148608.html