Last active
November 19, 2020 13:32
-
-
Save cbdyzj/00bf90ae5def3609c3831b107ec89c21 to your computer and use it in GitHub Desktop.
Insertion sort and selection sort benchmark
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.ThreadLocalRandom; | |
import java.util.stream.IntStream; | |
public class InsertionSortAndSelectionSort { | |
public static void main(String[] args) { | |
runBenchmarkN(1000); | |
runBenchmarkN(10000); | |
runBenchmarkN(100000); | |
} | |
private static void runBenchmarkN(int n) { | |
println(String.format("--- n = %s ---", n)); | |
println(); | |
println("Random Array"); | |
int[] randomIntArrayN = getRandomIntArray(n); | |
benchmark("InsertionSort", () -> insertionSort(randomIntArrayN.clone())); | |
benchmark("SelectionSort", () -> selectionSort(randomIntArrayN.clone())); | |
println(); | |
println("Ordered Array"); | |
int[] orderedIntArrayN = getOrderedIntArray(n); | |
benchmark("InsertionSort", () -> insertionSort(orderedIntArrayN.clone())); | |
benchmark("SelectionSort", () -> selectionSort(orderedIntArrayN.clone())); | |
println(); | |
} | |
private static void println(String s) { | |
System.out.println(s); | |
} | |
private static void println() { | |
System.out.println(); | |
} | |
private static void benchmark(String label, Runnable runnable) { | |
long start = System.currentTimeMillis(); | |
runnable.run(); | |
long end = System.currentTimeMillis(); | |
println(String.format("%s: %s s", label, (end - start) / 1000.0)); | |
} | |
private static int[] getRandomIntArray(int n) { | |
return ThreadLocalRandom.current().ints(0, Integer.MAX_VALUE).limit(n).toArray(); | |
} | |
private static int[] getOrderedIntArray(int n) { | |
int[] i = {0}; | |
return IntStream.generate(() -> i[0]++).limit(n).toArray(); | |
} | |
private static void insertionSort(int[] arr) { | |
for (int i = 1; i < arr.length; i++) { | |
int j = i - 1; | |
int t = arr[i]; | |
for (; j >= 0; j--) { | |
if (arr[j] <= t) { | |
break; | |
} | |
} | |
if (j < i - 1) { | |
int k = i; | |
while (k != j + 1) { | |
arr[k] = arr[k - 1]; | |
k--; | |
} | |
arr[j + 1] = t; | |
} | |
} | |
} | |
private static void selectionSort(int[] arr) { | |
for (int i = 0; i < arr.length - 1; i++) { | |
int c = i; | |
for (int j = i + 1; j < arr.length; j++) { | |
if (arr[j] < arr[c]) { | |
c = j; | |
} | |
} | |
if (c != i) { | |
int t = arr[i]; | |
arr[i] = arr[c]; | |
arr[c] = t; | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment