以整數升序排序為例來簡單說明一下雙向冒泡排序的過程:首先從前往后把最大數移到最后,然后反過來從后往前把最小的一個數移動到數組最前面,這一過程就是第一輪,然后重復這一過程,最終就會把整個數組從小到大排列好。雙向冒泡排序要稍微優於傳統的冒泡排序,因為雙向排序時數組的兩頭都排序好了,我們只需要處理數組的中間部分即可,而單向即傳統的冒泡排序只有尾部的元素是排好序的,這時每輪處理都需要從頭一直處理到已經排好序元素的前面一個元素。雖然它在效率上有了點改進,但它也不能大幅度提高其排序的效率,這是由冒泡排序的基本過程所決定了的。在此基礎上改進了一下,下面的代碼可以實現對奇數偶數分別排序
雙向冒泡排序源代碼:
1 package com.zc.manythread; 2 3 import java.util.Random; 4 5 /** 6 * 雙向冒泡排序 7 * @author 偶my耶 8 * 9 */ 10 public class BBSort { 11 12 13 //雙向冒泡算法,極大的減少了循環排序的次數 14 public int[] sort(int[] a)throws Exception{ 15 int j; 16 int limit=a.length; 17 int st=-1; 18 while(st<limit){ 19 //必須要給st和limit賦值,否則若數組一開始就有序 20 st++; 21 limit--; 22 boolean swapped=false; 23 //第一次循環將最大的值放到末尾 24 for (j = st ; j < limit; j++) { 25 if (a[j]>a[j+1]) { 26 int T=a[j]; 27 a[j]=a[j+1]; 28 a[j+1]=T; 29 swapped=true; 30 } 31 } 32 33 if (!swapped) { 34 return a; 35 }else { 36 swapped=false; 37 //第二次循環將最小的值放到了開頭 38 for (j = limit; --j>=st;) { 39 if(a[j]>a[j+1]){ 40 int T=a[j]; 41 a[j]=a[j+1]; 42 a[j+1]=T; 43 swapped=true; 44 } 45 } 46 if (!swapped) { 47 return a; 48 } 49 } 50 } 51 return a; 52 } 53 54 private static int[] createDate(int count) { 55 /** 56 * 無重復數組 57 */ 58 59 int[] data=new int[count]; 60 Random rand = new Random(); 61 boolean[] bool = new boolean[100]; 62 int num = 0; 63 for (int i = 0; i < count; i++) { 64 do { 65 // 如果產生的數相同繼續循環 66 num = rand.nextInt(100); 67 } while (bool[num]); 68 bool[num] = true; 69 /* list.add(num);*///list 列表 70 data[i]=num; 71 } 72 return data; 73 } 74 public static void main(String[] args) { 75 final int count=10; 76 int[] data=createDate(count); 77 for(int n : data){ 78 System.out.print(n+"\t"); 79 } 80 System.out.println(); 81 BSrot bsrot=new BSrot(data); 82 try { 83 84 int[] a=bsrot.sort(data); 85 for(int n : a){ 86 System.out.print(n+"\t"); 87 } 88 89 } catch (Exception e) { 90 // TODO Auto-generated catch block 91 e.printStackTrace(); 92 } 93 94 95 } 96 }
運行結果: