snow_xp
作者snow_xp·2010-09-29 10:54
系统工程师·

Java经典算法:鸡尾酒排序

字数 1757阅读 1614评论 0赞 0
问题
  有一数组,长度为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 > 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++;
  }
  }
  全部代码:
    package com.icescut.classic.algorithm;
  public class CocktailSort {
  public static void main(String[] args) {
  int[] array = { 10, -3, 5, 34, -34, 5, 0, 9 }; // 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 > 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;
  array = array[j];
  array[j] = tmp;
  }
  }

如果觉得我的文章对您有用,请点赞。您的支持将鼓励我继续创作!

0

添加新评论0 条评论

Ctrl+Enter 发表

作者其他文章

相关文章

相关问题

相关资料

X社区推广