刚刚开刷红宝书,好奇测了一下发现 Java 实现的选择排序比插入排序速度快,个人推测是 JVM 上交换位置操作比对比操作消耗大。 当然还是担心是我自己粗心导致的,请大家帮忙看下, tldr 的可以直接看最后面的运行结果。
public static void sort(Comparable[] a) {
int min = 0;
for (int i = 0; i < a.length; i++) {
min = i;
for (int j = i + 1; j < a.length; j++) {
if (less(a[j], a[min])) {
min = j;
}
}
exch(a, i, min);
}
}
public static void sort(Comparable[] a) {
for (int i = 0; i < a.length - 1; i++) {
for (int j = i + 1; j > 0; j--) {
if (less(a[j], a[j-1])) {
exch(a, j, j - 1);
} else {
break;
}
}
}
}
public static void timeTest(int n, int repeat) {
double selectionSortTime = 0;
long compareInSelection = 0;
long swapInSelection = 0;
double bubbleSortTime = 0;
double insertionSortTime = 0;
long compareInInsertion = 0;
long swapInInsertion = 0;
for (int i = 0; i < repeat; i++) {
Integer[] arr0 = genRandomArray(n);
Integer[] arr1 = copyArray(arr0);
Integer[] arr2 = copyArray(arr0);
Stopwatch stopwatch0 = new Stopwatch();
SelectionSort.sort(arr0);
selectionSortTime += stopwatch0.elapsedTime();
compareInSelection += SelectionSort.compare;
swapInSelection += SelectionSort.swap;
Stopwatch stopwatch1 = new Stopwatch();
BubbleSort.sort(arr1);
bubbleSortTime += stopwatch1.elapsedTime();
Stopwatch stopwatch2 = new Stopwatch();
InsertionSort.sort(arr2);
insertionSortTime += stopwatch2.elapsedTime();
compareInInsertion += InsertionSort.compare;
swapInInsertion += InsertionSort.swap;
}
StdOut.printf("algorithm avg compare swap\n");
StdOut.printf("SelectionSort %f %d %d\n", selectionSortTime / repeat, compareInSelection / repeat, swapInSelection / repeat);
StdOut.printf("BubbleSort %f \n", bubbleSortTime / repeat);
StdOut.printf("InsertionSort %f %d %d\n", insertionSortTime / repeat, compareInInsertion / repeat, swapInInsertion / repeat);
}
algorithm avg compare swap
SelectionSort 0.001032 499500 1000
BubbleSort 0.001788
InsertionSort 0.001293 250824 249831
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.