算法——冒泡排序

package test;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**算法思想:依次比較相鄰兩個元素,如果他們的順序錯誤就把他們調換過來,直到沒有元素再需要交換,排序完成。**/
public class Algorithm {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		List<Integer> array = new ArrayList<Integer>();
		array = getRandomList(10, 100);
		bubbleSort(array);
		System.out.println(array.toString());

	}

	/**
	 * 冒泡排序
	 * 
	 * @Title bubbleSort
	 * @param array需要排序的數據
	 * @Author: YHM
	 */
	static void bubbleSort(List<Integer> array) {
		for (int i = 0; i < array.size() - 1; i++) {
			boolean flag = true;// true 表示此次循環沒有交換,待排序列已經有序,排序結束
			for (int j = 0; j < array.size() - 1 - i; j++) {
				if (array.get(j) > array.get(j + 1)) {
					swap(array, j, j + 1);
					flag = false;
				}
			}
			if (flag) {
				break;
			}
		}
	}

	/**
	 * 交換數組中兩個數的位置
	 * 
	 * @Title swap
	 * @param array數組
	 * @param i索引
	 * @param j索引
	 * @Author: YHM
	 */
	static void swap(List<Integer> array, int i, int j) {
		array.set(i, array.get(i) + array.get(j));
		array.set(j, array.get(i) - array.get(j));
		array.set(i, array.get(i) - array.get(j));
	}

	/**
	 * 不帶種子,每次的隨機數不同
	 * 
	 * @Title getRandomList
	 * @param count產生的隨機數的個數
	 * @param max產生的隨機數的範圍
	 * @return 隨機數列表
	 * @Author: YHM
	 */
	static ArrayList<Integer> getRandomList(int count, int max) {
		ArrayList<Integer> list = new ArrayList<>();
		Random rand = new Random();
		for (int i = 0; i < count; i++) {
			int temp = rand.nextInt(max);
			list.add(temp);
		}

		return list;
	}

	/**
	 * 帶種子,每次的隨機數相同
	 * 
	 * @Title getRandomList
	 * @param count產生的隨機數的個數
	 * @param max產生的隨機數的範圍
	 * @return 隨機數列表
	 * @Author: YHM
	 */
	static ArrayList<Integer> getRandomList(int count, int max, int seed) {
		ArrayList<Integer> list = new ArrayList<>();
		Random rand = new Random(seed);
		for (int i = 0; i < count; i++) {
			int temp = rand.nextInt(max);
			list.add(temp);
		}

		return list;
	}

	/**
	 * 生成完全不重複的隨機數
	 * 
	 * @Title getRandomList
	 * @param count產生的隨機數的個數
	 * @param max產生的隨機數的範圍
	 * @return 隨機數列表
	 * @Author: YHM
	 */
	static ArrayList<Integer> getRandomListNoRepeat(int count, int max) {
		ArrayList<Integer> list = new ArrayList<>();
		SecureRandom rand = new SecureRandom();
		for (int i = 0; i < count; i++) {
			int temp = rand.nextInt(max);
			list.add(temp);
		}

		return list;
	}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章