您的位置:首页 > 其它

基于交换的排序算法

2013-07-07 15:56 141 查看
基于交换的排序算法:冒泡排序,快速排序。

冒泡排序:总的时间复杂度O(n2)

/*
* 冒泡排序
*/
public static void bubbleSort(int[] array, int length){
for(int i=1; i<length; i++){
for(int j=0;j<length-i;j++){
if(array[j]>array[j+1]){
int temp = array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
}
}


快速排序:通过选择pivot(枢轴或者支点),将原始数组分为两部分,前一部分比pivot小,后一部分比pivot大,然后递归下去,最终得到排好序的数组。
代码中,是默认选择数组的第一个元素作为pivot的。

平均时间复杂度:O(n*logn)

若初始数组基本有序,选择第一个作为pivot,快速排序将蜕化为冒泡排序,因此对于pivot的选取非常重要,通常是从start, middle, end三个数组元素中选择其中一个。

/*
* 快速排序
*/
public void quickSort(int[] array, int start, int end ){
if(start<end){
int pivotKey=pivotKey(array,start,end);
quickSort(array,start,pivotKey-1);
quickSort(array,pivotKey+1,end);
}

}

public int pivotKey(int[] array, int start, int end){
int temp=array[start];
while(start<end){
while(start<end&&temp<=array[end]) end--;
array[start]=array[end];
while(start<end&&temp>=array[start])start++;
array[end]=array[start];
}

array[start]=temp;

return start;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: