TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
问题 有一数组,长度为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
++
;
}
}
全部代码:  Code
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;
}
}
源码下载:http://file.javaxxz.com/2014/11/13/000606656.zip |
|