`
crespo1414
  • 浏览: 2907 次
  • 性别: Icon_minigender_1
  • 来自: 南京
最近访客 更多访客>>
社区版块
存档分类
最新评论

冒泡排序与快速排序

 
阅读更多

首先是冒泡排序

import java.util.Random;

public class BubbleSort {

	private static int score[] = new int[50000];

	static {
		for (int i = 0; i < score.length - 1; i++) {
			Random r = new Random();
			score[i] = r.nextInt(100);
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		long start = System.currentTimeMillis();
		for (int i = 0; i < score.length - 1; i++) {
			for (int j = 0; j < score.length - i - 1; j++) {
				if (score[j] > score[j + 1]) {
					int tmp = score[j];
					score[j] = score[j + 1];
					score[j + 1] = tmp;
				}
			}

		}
		
		for (int a = 0; a < score.length; a++) {
			System.out.print(score[a] + "\t");
		}
		System.out.println("");

		System.out.println(System.currentTimeMillis() - start);
	}

}

 执行结果,处理了 7351毫秒

 

快速排序:

import java.util.Random;

public class QuickSort {
	private static int score[] = new int[50000];

	static {
		for (int i = 0; i < score.length - 1; i++) {
			Random r = new Random();
			score[i] = r.nextInt(100);
		}
	}

	public static void main(String[] args) {
		long start = System.currentTimeMillis();
		quickSort(score, 0, score.length - 1);
		for (int i : score) {
			System.out.print(i + "\t");
		}
		System.out.println("");

		System.out.println(System.currentTimeMillis() - start);
	}

	public static void quickSort(int[] datas, int low, int high) {
		if (low < high) {
			int middle = getMiddle(datas, low, high);
			quickSort(datas, low, middle - 1);
			quickSort(datas, middle + 1, high);
		}
	}

	public static int getMiddle(int[] datas, int low, int high) {
		int tmp = datas[low];
		while (low < high) {
			while (low < high && tmp <= datas[high]) {
				high--;
			}
			datas[low] = datas[high];

			while (low < high && tmp >= datas[low]) {
				low++;
			}
			datas[high] = datas[low];
		}
		datas[low] = tmp;
		return low;
	}
}

 

执行结果看 仅仅消耗 147毫秒

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics