标签:
public class MainTest {
public static void main(String[] args) {
int[] arr1 = { 121, 66, 24, 18, 94, 31, 55, 22, 37, 53, 89 };
Arrays.sort(arr1);
for (int i = 0; i < arr1.length; i++) {
System.out.print(" " + arr1[i] + " ");
}
System.out.println();
// 鸡尾酒排序法
int[] sorts = { 21, 101, 33, 55, 64, 27, 87, 23, 69, 54, 32 };
sorts = cocktailSort(sorts);
int[] sortsq = new int[sorts.length];
int j = 0;
for (int i = sorts.length - 1; i >= 0; i--) {
sortsq[j] = sorts[i];
j++;
}
print(sortsq);
System.out.println();
// 合并数组
int[] merge = MergeList(arr1, sortsq);
if (merge != null) {
print(merge);
}
}
/**
* 鸡尾酒排序 数组中的数字本是无规律的排放,先找到最小的数字, 把他放到第一位, 然后找到最大的数字放到最后一位。然后再找到第二小的数字放到第二位,
* 再找到第二大的数字放到倒数第二位。以此类推,直到完成排序。 时间复杂度O(n2)
*
* @param src
* 无序的数组
* @return 从大到小的数组
*/
public static int[] cocktailSort(int[] src) {
// 将最小值排到队尾
for (int i = 0; i < src.length / 2; i++) {
for (int j = i; j < src.length - i - 1; j++) {
if (src[j] < src[j + 1]) {
int temp = src[j];
src[j] = src[j + 1];
src[j + 1] = temp;
}
}
// 将最大值排到队头
for (int j = src.length - 1 - (i + 1); j > i; j--) {
if (src[j] > src[j - 1]) {
int temp = src[j];
src[j] = src[j - 1];
src[j - 1] = temp;
}
}
}
return src;
}
/**
* 合并两个数组
*
* @param a数组
* @param b数组
* @return 合并在一起的数组
*/
public static int[] MergeList(int a[], int b[]) {
int result[];
// 检查传入的数组是否是有序的
if (checkSort(a) && checkSort(b)) {
result = new int[a.length + b.length];
int i = 0, j = 0, k = 0; // i:用于标示a数组 j:用来标示b数组 k:用来标示传入的数组
while (i < a.length && j < b.length)
if (a[i] <= b[j]) {
result[k++] = a[i++];
} else {
result[k++] = b[j++];
}
/* 后面连个while循环是用来保证两个数组比较完之后剩下的一个数组里的元素能顺利传入 */
while (i < a.length) {
result[k++] = a[i++];
}
while (j < b.length) {
result[k++] = b[j++];
}
return result;
} else {
System.out.print("非有序数组,不可排序!");
return null;
}
}
/**
* 检查数组是否是顺序存储的
* @param a 数组
* @return true / false
*/
public static boolean checkSort(int a[]) {
boolean change = true; // 这个标志位是一种优化程序的方法,可以看看我写的冒泡排序优化就会明白了
for (int i = 0; i < a.length - 1 && change; i++) {
for (int j = i + 1; j < a.length; j++)
if (a[j - 1] > a[j])
return false;
else
change = false;
}
return true;
}
// 打印函数
public static void print(int b[]) {
for (int i = 0; i < b.length; i++) {
System.out.print(" " + b[i] + (i % 10 == 9 ? " " : " "));
}
}
}
标签:
原文地址:http://my.oschina.net/u/1475665/blog/471030