冒泡排序

package sort;

public class BubbleSort {

	private int[] array;
	private int maxSize;

	public BubbleSort(int maxSize) {
		this.array = new int[maxSize];
		this.maxSize = maxSize;
	}

	private int[] getRandomNum() {
		for (int i = 0; i < maxSize; i++) {
			array[i] = (int) Math.round(Math.random() * 1000);
		}
		return array;
	}

	private void getSortedNum() {
		int i, j;
		for (i = array.length - 1; i > 0; i--) {
			for (j = 0; j < i; j++) {
				if (array[j] > array[j + 1]) {
					swapNum(j, j + 1);
				}
			}
		}
	}

	// private void getSortedNum() {
	// int i, j;
	// for (i = 1; i < array.length; i++) {
	// for (j = 0; j < array.length - i; j++) {
	// if (array[j] > array[j + 1]) {
	// swapNum(j, j + 1);
	// }
	// }
	// }
	// }

	private void swapNum(int subScriptA, int subScriptB) {
		int tempNum;
		tempNum = array[subScriptA];
		array[subScriptA] = array[subScriptB];
		array[subScriptB] = tempNum;
	}

	public static class BubbleSortApp {
		public static void main(String[] args) {
			int maxSize = 1000;
			BubbleSort bs = new BubbleSort(maxSize);
			String strs = "";

			bs.getRandomNum();
			for (int i = 0; i < bs.array.length - 1; i++) {
				strs += bs.array[i] + ",";
			}
			strs += bs.array[bs.array.length - 1];
			System.out.println("sort :      " + strs);

			strs = "";
			bs.getSortedNum();

			for (int i = 0; i < bs.array.length - 1; i++) {
				strs += bs.array[i] + ",";
			}
			strs += bs.array[bs.array.length - 1];
			System.out.println("sorted : " + strs + "\n");
		}
	}
}

  

posted @ 2012-07-25 16:44  雲端之風  阅读(555)  评论(1编辑  收藏  举报