冒泡法排序和插入法排序的效率比较


冒泡法排序

public class Bubble {
	public static void main(String[] args) {
		int[] a = { 2, 1, 4, 5, 6, 7, 8, 9, 23, 44 };
		long start =System.currentTimeMillis();
		for(int i=0;i<10000;i++){
		 sort(a);
		}
		 long end = System.currentTimeMillis();
		 System.out.println(end-start);
		for (int i = 0; i < a.length; i++) {
			System.out.print(a[i] + " < ");
		}
	}

	private static void sort(int[] a) {
		for (int i = 0; i < a.length; i++) {
			for (int j = 0; j < a.length - 1 - i; j++) {
				if (a[j] > a[j + 1]) {
					int temp = a[j];
					a[j] = a[j + 1];
					a[j + 1] = temp;
				}
			}
		}
	}

}

 插入法排序

package xuexi;

public class Insert {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] data = { 2, 1, 4, 5, 6, 7, 8, 9, 23, 44 };
		long start =System.currentTimeMillis();
		for(int i=0;i<10000;i++){
		 sort(data);
		}
		 long end = System.currentTimeMillis();
		 System.out.println(end-start);
		for(int i=0;i < data.length;i++){
		System.out.print(data[i] + " > ");
		}
		}

	public static void sort(int[] data) {// 方法得是静态的
		int temp;
		for (int i = 1; i < data.length; i++) {
			for (int j = i; (j > 0) && (data[j] > data[j - 1]); j--) {

				temp = data[j];
				data[j] = data[j - 1];
				data[j - 1] = temp;
			}
		}
	}

}

 排序时间差不少呢!

你可能感兴趣的:(J#)