/**
* 快速排序
* @author neu_fufengrui@163.com
*
*/
public class QuickSort {
private QuickSort(){
}
/**
* 冒泡排序--下沉式气泡排序
* 时间复杂度O(n2)
* 空间复杂度O(1)
*/
public static void sort(int a[], int off, int len){
for(int i = off; i < len; i++){
for(int j = off; j < len-i; j++){
if(a[j] > a[j+1]){
swap(a, j, j+1);
}
}
print(a);
}
}
/*output ~.~
11,12,5,31,30,26,34,36,18,38,
11,5,12,30,26,31,34,18,36,38,
5,11,12,26,30,31,18,34,36,38,
5,11,12,26,30,18,31,34,36,38,
5,11,12,26,18,30,31,34,36,38,
5,11,12,18,26,30,31,34,36,38,
5,11,12,18,26,30,31,34,36,38,
5,11,12,18,26,30,31,34,36,38,
5,11,12,18,26,30,31,34,36,38,
*/
/**
* 冒泡排序--上升时气泡排序
* 时间复杂度O(n2)
* 空间复杂度O(1)
*/
public static void sort1(int a[], int off, int len){
for(int i = off; i < len; i++){
for(int j = len; j > i; j--){
if(a[j] < a[j-1]){
swap(a, j, j-1);
}
}
print(a);
}
}
/*output ~.~
5,11,31,12,18,34,30,26,38,36,
5,11,12,31,18,26,34,30,36,38,
5,11,12,18,31,26,30,34,36,38,
5,11,12,18,26,31,30,34,36,38,
5,11,12,18,26,30,31,34,36,38,
5,11,12,18,26,30,31,34,36,38,
5,11,12,18,26,30,31,34,36,38,
5,11,12,18,26,30,31,34,36,38,
5,11,12,18,26,30,31,34,36,38,
*/
/**
* 快速排序
* 通过一趟排序,将记录分成独立的两部分,其中一部分的关键字均比另一部分小,分别对两部分继续排序,达到整体有序的目的
* 与序列有关,平均时间复杂度:O(nlogn),最差退化为冒泡排序:O(n2)
* 空间复杂度:O(logn),一个栈空间
*/
public static void sort2(int a[], int low, int high){
print(a);
if(low < high){
int mid = partition(a, low, high);//二分排序,并返回中间位置
sort2(a, low, mid-1);//递归排序,小的部分
sort2(a, mid+1, high);//递归排序,大的部分
}
}
private static int partition(int a[], int low, int high){
int temp = a[low];
while(low < high){
while(low < high && a[high] >= temp){
high --;
}
a[low] = a[high];
while(low < high && a[low] <= temp){
low ++;
}
a[high] = a[low];
}
a[low] = temp;
return low;
}
private static void swap(int a[], int index, int index2){
int temp = a[index];
a[index] = a[index2];
a[index2] = temp;
}
public static void print(int a[]){
for(int i : a){
System.out.print(i+",");
}
System.out.println();
}
public static void main(String[] args) {
int a[] = {11, 31, 12, 5, 34, 30, 26, 38, 36, 18};
QuickSort.sort(a, 0, a.length - 1);
QuickSort.sort1(a, 0, a.length - 1);
QuickSort.sort2(a, 0, a.length - 1);
}
}