package audition.lyx.sort;
/**
*
* @author: liyixiang
* @data:2014-9-25
* @题目大意:
* 快速排序
* @主要思路:
* 分治法 选取一个元素作为中间值,与其他元素比较,如果小于中间元素,则放在中间元素
* 左边,否则放在中间元素右边,之后分别为左边,右边元素排序,排完序合并两段元素即可。
* @时间复杂度:
* O(nlogn) 最差情况(待排数组正或逆序) O(n^2)
* @空间复杂度:
* O(logn) 最差情况(待排数组正或逆序) O(n)
*/
public class QuickSort {
/**
*
* 方法概述:
* 参数:
* 返回值:
*/
public void quickSort(int data[],int start,int end){
int pivot = start; //作为中间元素
int i = start + 1; //左边索引
int j = end; //右边索引
while(true){
if (start >= end) //判断左右端是否排序完毕,防止出现数组越界异常
return;
/*
* 双向指针向中间聚集
*/
while(i <= end && data[i]
i++;
}
while(j > start && data[j] > data[pivot]){
j--;
}
//交换元素
if(i
int temp = data[i];
data[i] = data[j];
data[j] = temp;
}else {
break;
}
}
//交换到中间位置 形成左端比其小,有端比其大
int temp = data[start];
data[start] = data[j];
data[j] = temp;
quickSort(data,start,j-1); //中间值左序列排序
quickSort(data,j+1,end); //中间值右序列排序
}
public static void main(String[] args) {
int data[] = {3,6,4,1,2,5,7};
new QuickSort().quickSort(data, 0, data.length-1);
for(int i=0;i
System.out.print(data[i]);
}
}
}