最近一直看到排序这个关键字,就准备开始读《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;
}
}
}
}
}