冒泡排序 和 雞尾酒排序的區別 ?


 一, 冒泡排序 :

代碼如下:

 1 package sort;
 2 /**
 3  * 冒泡排序
 4  * @author DHY
 5  * @creation 2018年5月15日
 6  */
 7 
 8 public class BubbleSort {
 9     
10         public void bubble(Integer[] data){
11             
12             for(int i=0;i<data.length;i++){
13                 
14                 for(int j=0;j<data.length-1-i;j++){
15                     if(data[j]>data[j+1]){   //如果后一個數小於前一個數交換
16                         int tmp=data[j];
17                         data[j]=data[j+1];
18                         data[j+1]=tmp;
19                     }
20                 }
21                 
22             }
23             
24         }
25     
26         
27     /**測試代碼*/
28     public static void main(String[] args) {
29 
30              Integer[] list={49,38,65,97,76,13,27,14,10};
31              //冒泡排序
32              BubbleSort bs=new BubbleSort();
33              bs.bubble(list);
34              
35              for(int i=0;i<list.length;i++){
36                  System.out.print(list[i]+" ");
37              }
38              System.out.println();
39         }
40 
41     
42 
43 }
View Code

 


 

二,雞尾酒排序:

與冒泡排序不同的地方

  雞尾酒排序,即雙向的冒泡排序,等於是冒泡排序的輕微變形。不同的地方在於從低到高然后從高到低(有先后順序,並非同時;大循環下第一個循環是從開始掃到結束,將最大的歸到最后;第二個循環是從倒數第二個位置往開始端掃,將最小的歸到開始的位置),而冒泡排序則僅僅從低到高去比較序列里的每個元素。他可以得到比冒泡排序稍微好一點的效能,原因是冒泡排序只從一個方向進行比對(由低到高),每次只移動一個項目和。   以排序(49,38,65,97,76,13,27,14,10)為例,雞尾酒排序只要訪問一次序列就可以完成排序,但如果使用冒泡排序需要八次。但是在亂數序列的狀態下,雞尾酒排序和冒泡排序的效率都很差。

 

 代碼如下:

 1 package sort;
 2 public class CocktailSort {
 3     /**測試代碼*/
 4     public static void main(String args[]) {  
 5 //        int[] numbers={-1, 0, 50, 44, -90};
 6         int[] numbers={49,38,65,97,76,13,27,14,10};
 7         sort(numbers);
 8         for(int number : numbers) { 
 9             System.out.println(number); 
10         } 
11     }
12     /**雞尾酒排序*/
13     static void sort(int[] numbers){
14         int temp;
15         int m=0,n=numbers.length-1;
16         while(m<n){
17             for(int i=m; i<n;i++){
18                 if(numbers[i]>numbers[i+1]){
19                     //交換數組中兩個數字的位置
20                     temp=numbers[i];
21                     numbers[i]=numbers[i+1];
22                     numbers[i+1]=temp;
23                 }
24             }
25             n--;
26             for(int i=n; i>m;i--){
27                 if(numbers[i]<numbers[i-1]){
28                     //交換數組中兩個數字的位置
29                     temp=numbers[i];
30                     numbers[i]=numbers[i-1];
31                     numbers[i-1]=temp;
32                 }
33             }
34             m++;
35         }    
36     }
37 }
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM