Posts Tagged InsertionSort

InsertionSort

More efficient in practice than most other simple O(n2) algorithms such as selection sort or bubble sort: the average time is n2/4 and it is linear in the best case
Stable (does not change the relative order of elements with equal keys)
In-place (only requires a constant amount O(1) of extra memory space)
It is an online algorithm, in that it can sort a list as it receives it. if
an array is sorted or nearly sorted, insertion sort will significantly outperform quicksort.
Insertion sort takes O(n2) time in the worst case as well as in the average case which makes it impractical for sorting large numbers of elements

public class InsertionSort {
public int[] sort(int[] data) {
for (int i = 1; i = 0 && data[j] > target; j--) {
data[j + 1] = data[j];
}
data[j + 1] = target;
}
return data;
}
public static void main(String[] args) {
int[] data = new int[] { 8, 16, 15, 42, 23, 4 };
System.out.println(Arrays.toString(new InsertionSort().sort(data)));
}
}

Leave a Comment