/*
* @(#)bubbleSort.java 1.01 09/11/24
*
* Copyright 2009 Three Stone.company, Inc. All rights reserved.
* PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
* this function implement as(-9 -4 0 7 4 -2 0 3 8)to(-9 -4 -2 3 4 7 8 0 0)sort code.
*/
package edu.sort;
public class bubbleSort {
/**
* @see
* @param args
* @author GL
* @category:实现随机给出带有正负整数的数组由小到大的排序(负数->正数->0)
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int array[] = new int[20];//初始化数组
for (int i = 0; i < array.length; i++) {
int number = (int) (Math.random() * 10 * (Math.pow(-1, (int) (Math
.random() * 10))));//初始化随机正负数
array[i] = number;
}
System.out.println("初始序列为:");
printNumbers(array);
array = bubble(array);//排序方法调入
System.out.println("最后的排序为:");
printNumbers(array);
}
/**
* @param array[]
* @author GL
* @category 冒泡排序并将所有0置后
*/
public static int[] bubble(int array[]) {
int length = array.length;
for (int i = 0; i < length; i++) {
for (int j = length - 1; j > i; j--) {
if (array[j] < array[j - 1]) {//冒泡原理"大小"换成"小大"
int temp = array[j];
array[j] = array[j - 1];
array[j - 1] = temp;
}
}
}
System.out.println("冒泡排序结果为:");
printNumbers(array);
int count = 0;//记录数组中0的个数
int start = 0;//记录0在数组中的初始出现位置
for (int i = 0; i < array.length; i++) {
if (array[i] == 0 && array[i - 1] != 0) {
start = i + 1;
count = 1;
System.out.println("第" + start + "位出现0");
} else if (array[i] == 0 && array[i - 1] == 0) {
count++;
}
}
System.out.println("0的个数为:" + count + "个");
if (start != 0 && count != 0) {//按照0的初始出现位置与0的个数顺次移动元素
for (int i = (start - 1); i < array.length; i++) {
if (i < (array.length - count)) {
array[i] = array[i + count];
} else { //最后将数组后count位置0
array[i] = 0;
}
}
}
return array;
}
/**
* @param array[]
* @author GL
* @category 输出情况讨论
*/
public static void printNumbers(int array[]) {
for (int i = 0; i < array.length; i++) {
if ((((i + 1) % 10) == 1) && array[i] >= 0) {//首位
System.out.print(" " + array[i] + " ");
} else if ((i + 1) % 10 != 0 && array[i + 1] < 0) {//非尾负数
System.out.print(array[i] + " ");
} else if ((i + 1) % 10 != 0 && array[i + 1] >= 0) {//非尾正数
System.out.print(array[i] + " ");
} else {
System.out.println(array[i]);//尾数
}
}
}
}