Intro
So this time I wanted to find out which of the two insertion sort flavours are faster:
Code
io.github.coderodde.util.StraightInsertionSort.java:
package io.github.coderodde.util;
/**
* This class provides static methods for sorting integer arrays via insertion
* sort and so called <b>straight</b> insertion sort.
*
* @author Rodion "rodde" Efremov
* @version 1.0.0 (Sep 18, 2025)
* @since 1.0.0 (Sep 18, 2025)
*/
public final class StraightInsertionSort {
private StraightInsertionSort() {
}
public static void insertionSort(int[] array) {
for (int i = 1; i < array.length; ++i) {
int j = i;
while (j > 0 && array[j - 1] > array[j]) {
swap(array, j - 1, j);
--j;
}
}
}
public static void straightInsertionSort(int[] array) {
for (int i = 1; i < array.length; ++i) {
int x = array[i];
int j = i;
while (j > 0 && array[j - 1] > x) {
array[j] = array[j - 1];
--j;
}
array[j] = x;
}
}
private static void swap(int[] array, int i, int j) {
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
io.github.coderodde.util.bench.java:
package io.github.coderodde.util.benchmark;
import io.github.coderodde.util.StraightInsertionSort;
import java.util.Arrays;
import java.util.Random;
public final class Benchmark {
private static final int LENGTH = 20_000;
public static void main(String[] args) {
int[] arr1 = getRandomArray(LENGTH, new Random());
int[] arr2 = arr1.clone();
long ta = System.currentTimeMillis();
StraightInsertionSort.insertionSort(arr1);
long tb = System.currentTimeMillis();
System.out.println(
"Ordinary insertion sort: " + (tb - ta) + " milliseconds.");
ta = System.currentTimeMillis();
StraightInsertionSort.straightInsertionSort(arr2);
tb = System.currentTimeMillis();
System.out.println(
"Straight insertion sort: " + (tb - ta) + " milliseconds.");
System.out.println("Algorithms agree: " + (Arrays.equals(arr1, arr2)));
}
private static int[] getRandomArray(int length, Random random) {
int[] array = new int[length];
for (int i = 0; i < array.length; ++i) {
array[i] = random.nextInt();
}
return array;
}
}
Typical output
I got this occasionally:
Ordinary insertion sort: 124 milliseconds.
Straight insertion sort: 61 milliseconds.
Algorithms agree: true
Critique request
Could you please review my benchmark runner?