java 鸡尾酒排序_java交换排序之鸡尾酒排序实现方法
本文實(shí)例講述了java交換排序之雞尾酒排序?qū)崿F(xiàn)方法。分享給大家供大家參考。具體如下:
雞尾酒排序,也就是定向冒泡排序, 雞尾酒攪拌排序, 攪拌排序 (也可以視作選擇排序的一種變形), 漣漪排序, 來(lái)回排序 or 快樂(lè)小時(shí)排序, 是冒泡排序的一種變形。此算法與冒泡排序的不同處在于排序時(shí)是以雙向在序列中進(jìn)行排序。
與冒泡排序不同的地方:
雞尾酒排序等于是冒泡排序的輕微變形。不同的地方在于從低到高然后從高到低,而冒泡排序則僅從低到高去比較序列里的每個(gè)元素。他可以得到比冒泡排序稍微好一點(diǎn)的效能,原因是冒泡排序只從一個(gè)方向進(jìn)行比對(duì)(由低到高),每次循環(huán)只移動(dòng)一個(gè)項(xiàng)目。
以序列(2,3,4,5,1)為例,雞尾酒排序只需要訪問(wèn)一次序列就可以完成排序,但如果使用冒泡排序則需要四次。 但是在亂數(shù)序列的狀態(tài)下,雞尾酒排序與冒泡排序的效率都很差勁。
最差時(shí)間復(fù)雜度? O(n^2)
最優(yōu)時(shí)間復(fù)雜度?O(n)
平均時(shí)間復(fù)雜度?? O(n^2)
雞尾酒排序動(dòng)態(tài)圖如下:
代碼分析:
package com.baobaotao.test;
/**
* 排序研究
*
*/
public class Sort {
/**
* 經(jīng)典雞尾酒排序
* @param array 傳入的數(shù)組
*/
public static void cocatailSort(int[] array) {
int length = array.length ;
//來(lái)回循環(huán)length/2次
for(int i=0;i
for(int j=i;j
if(array[j] > array[j+1]) {
swap(array, j, j+1) ;
}
}
for(int j=length-i-1;j>i;j--) {
if(array[j] < array[j-1]) {
swap(array, j-1, j) ;
}
}
printArr(array) ;
}
}
/**
* 雞尾酒排序(帶標(biāo)志位)
* @param array 傳入的數(shù)組
*/
public static void cocatailSortFlag(int[] array) {
int length = array.length ;
boolean flag1,flag2 = true ;
//來(lái)回循環(huán)length/2次
for(int i=0;i
flag1 = true ;
flag2 = true ;
for(int j=i;j
if(array[j] > array[j+1]) {
swap(array, j, j+1) ;
flag1 = false ;
}
}
for(int j=length-i-1;j>i;j--) {
if(array[j] < array[j-1]) {
swap(array, j-1, j) ;
flag2 = false ;
}
}
if(flag1 && flag2) {
break ;
}
printArr(array) ;
}
}
/**
* 按從小到大的順序交換數(shù)組
* @param a 傳入的數(shù)組
* @param b 傳入的要交換的數(shù)b
* @param c 傳入的要交換的數(shù)c
*/
public static void swap(int[] a, int b, int c) {
int temp = 0 ;
if(b < c) {
if(a[b] > a[c]) {
temp = a[b] ;
a[b] = a[c] ;
a[c] = temp ;
}
}
}
/**
* 打印數(shù)組
* @param array
*/
public static void printArr(int[] array) {
for(int c : array) {
System.out.print(c + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] number={11,95,45,15,78,84,51,24,12} ;
int[] number2 = {11,95,45,15,78,84,51,24,12} ;
cocatailSort(number) ;
System.out.println("*****************");
cocatailSortFlag(number2) ;
}
}
結(jié)果分析:
11 12 45 15 78 84 51 24 95
11 12 15 24 45 78 51 84 95
11 12 15 24 45 51 78 84 95
11 12 15 24 45 51 78 84 95
*****************
11 12 45 15 78 84 51 24 95
11 12 15 24 45 78 51 84 95
11 12 15 24 45 51 78 84 95
可見(jiàn)雞尾酒排序排序的次數(shù)比普通冒泡排序要少很多。只需要4次,用了改進(jìn)版的標(biāo)志位雞尾酒排序僅需要3次就可以完成排序。
希望本文所述對(duì)大家的java程序設(shè)計(jì)有所幫助。
總結(jié)
以上是生活随笔為你收集整理的java 鸡尾酒排序_java交换排序之鸡尾酒排序实现方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 上海杉达学院计算机课程,上海杉达学院计算
- 下一篇: 震惊!!!“达叔”亲临指导----带你轻