经典算法之鸡尾酒排序

 

问题

    有一数组,长度为n,把数组中的元素从小到大重新排列。

 

说明

    鸡尾酒(cocktail)排序,又叫搅拌(shaker)排序。是改良的冒泡排序,冒泡排

序可见本人的另一篇文章经典算法之冒泡排序

 

思路

    鸡尾酒排序的过程为:(1)先对数组从左到右进行冒泡排序(升序),则最大的元

素去到最右端;(2)再对数组从右到左进行冒泡排序(降序),则最小的元素去到最左

端。以此类推,依次改变冒泡的方向,并不断缩小未排序元素的范围。

    例如对45 ,19, 77, 81, 13, 28, 18, 19, 77进行排序

    从左到右:19,45,77,13,28,18,19,77,81

    从右到左:13,19,45,77,18,28,19,77,81

    从左到右:13,19,45,18,28,18,77,77,81

    从右到左:13,18,19,45,18,28,77,77,81

    从左到右:13,18,19,18,28,45,77,77,81

    从右到左:13,18,18,19,28,45,77,77,81

    这时不再发生交换,排序结束。

 

核心代码:

static   void  sort( int [] array) {
        
int  top  =  array.length  -   1 ;
        
int  bottom  =   0 ;
        
boolean  flag  =   true ;
        
int  i, j;
        
while  (flag) {
            flag 
=   false ;
            
// 从小到大,升序
             for  (i  =  bottom; i  <  top; i ++ ) {
                
if  (array[i]  >  array[i  +   1 ]) {
                    swap(array, i, i 
+   1 );
                    flag 
=   true ;
                }
            }
            top
-- ;
            
            
// 从大到小,降序
             for  (j  =  top; j  >  bottom; j -- ) {
                
if  (array[j]  <  array[j  -   1 ]) {
                    swap(array, j, j 
-   1 );
                    flag 
=   true ;
                }
            }
            bottom
++ ;
        }
    }

 

全部代码:

ContractedBlock.gif ExpandedBlockStart.gif Code
package com.icescut.classic.algorithm;

public class CocktailSort {

    
public static void main(String[] args) {
        
int[] array = { 10-3534-34509 }; // test data
        sort(array);
        
for (int el : array) {
            System.out.print(el 
+ " ");
        }
    }
    
    
static void sort(int[] array) {
        
int top = array.length - 1;
        
int bottom = 0;
        
boolean flag = true;
        
int i, j;
        
while (flag) {
            flag 
= false;
            
//从小到大,升序
            for (i = bottom; i < top; i++) {
                
if (array[i] > array[i + 1]) {
                    swap(array, i, i 
+ 1);
                    flag 
= true;
                }
            }
            top
--;
            
            
//从大到小,降序
            for (j = top; j > bottom; j--) {
                
if (array[j] < array[j - 1]) {
                    swap(array, j, j 
- 1);
                    flag 
= true;
                }
            }
            bottom
++;
        }
    }

    
private static void swap(int[] array, int i, int j) {
        
int tmp = array[i];
        array[i] 
= array[j];
        array[j] 
= tmp;
    }

}

转载于:https://www.cnblogs.com/icescut/archive/2009/11/13/CocktailSort.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值