O(1/2(n^2)) -> O(n^2). It is in-place sort. We find smallest value and move it to the front. It is not stable algorithm.
class SortArray {
static void main(String[] args) {
int[] array = [1, 5, 7, 3, 9, 1, -2]
println array
sort(array)
println array
}
static void sort(int[] array) {
int min
int temp
for (int i = 0; i < array.length; i++) {
min = i
for (int j = i + 1; j < array.length; j++) {
if (array[j] < array[min]) {
min = j
}
}
temp = array[i]
array[i] = array[min];
array[min] = temp;
}
}
}
Insertion Sort
Complexity is about O(1/4(n^2)) in optimistic case - when the array is partially sorted, this algorithm works perfectly In worst case, it is O(1/2(n^2)) - when the values in reversed order. In general, O(n^2). It is in-place and stable. For sorted list, the complexity is O(n).