鸡尾酒排序
鸡尾酒排序是冒泡排序的变体:循环一次排好两个数,最大最小的数分别置于首尾。
1 //鸡尾酒排序 2 public class CocktailSort 3 { 4 public void cocktailSort(int[] r) 5 { 6 int length=r.length; 7 boolean swaped=true; 8 for(int i=0;i<length/2 && swaped;i++) 9 { 10 swaped=false; 11 for(int j=i;j<length-i-1;j++)//最外层循环一次待排序序列的首尾都排好,一次循环最大最小的排好 12 { 13 if(r[j]>r[j+1])//将最大的元素放在末尾 14 { 15 int temp=r[j]; 16 r[j]=r[j+1]; 17 r[j+1]=temp; 18 swaped=true; 19 } 20 } 21 if(!swaped) break; 22 swaped=false;
for(int j=length-i-2;j>i;j--)//将最小的放在最前面 23 { 24 if(r[j]<r[j-1]) 25 { 26 int temp=r[j]; 27 r[j]=r[j-1]; 28 r[j-1]=temp; 29 swaped=true; 30 } 31 } 32 } 33 } 34 public static void main(String[] args) 35 { 36 CocktailSort c=new CocktailSort(); 37 int[] a={4,8,3,6,9,7,5,2,1}; 38 c.cocktailSort(a); 39 for(int i=0;i<a.length;i++) 40 System.out.print(a[i]+" "); 41 } 42 }