简单排序

最近一直看到排序这个关键字,就准备开始读《Java数据结构和算法》。

下面的代码包括冒泡排序、选择排序和插入排序。

对于随机数组,插入排序用时总是最短。

bubble用时:202 ms
select用时:185 ms
insert用时:60 ms

bubble用时:188 ms
select用时:183 ms
insert用时:60 ms

bubble用时:192 ms
select用时:189 ms
insert用时:61 ms

bubble用时:182 ms
select用时:189 ms
insert用时:61 ms

public class ArraySort {

	public static int[] createIntArray(int size) {
		int[] a = new int[size];
		for (int i = 0; i < size; i++) {
			a[i] = (int) (Math.random() * size);
		}
		return a;
	}

	public static void print(int[] a) {
		for (int i = 0; i < a.length; i++) {
			System.out.print(a[i] + " ");
		}
		System.out.println();
	}

	public static void bubbleSort(int[] a) {
		for (int out = a.length - 1; out > 0; out--) {
			for (int in = 0; in < out; in++) {
				if (a[in] > a[in + 1]) {
					int temp = a[in];
					a[in] = a[in + 1];
					a[in + 1] = temp;
				}
			}
		}
	}

	public static void selectSort(int[] a) {
		for (int out = a.length - 1; out > 0; out--) {
			int max = out;
			for (int in = 0; in < out; in++) {
				if (a[in] > a[max]) {
					max = in;
				}
			}
			int temp1 = a[out];
			a[out] = a[max];
			a[max] = temp1;
		}
	}

	public static void insertSort(int[] a) {
		for (int out = a.length - 1; out > 0; out--) {
			int tempValue = a[out - 1];
			for (int in = out; in < a.length; in++) {
				if (tempValue > a[in]) {
					a[in - 1] = a[in];
					if (in == a.length - 1) {
						a[in] = tempValue;
					}
				} else {
					a[in - 1] = tempValue;
					break;
				}
			}
		}
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值