冒泡排序与快速排序

首先是冒泡排序

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毫秒

发布了4 篇原创文章 · 获赞 0 · 访问量 1061
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览