Selection Sort
Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) time complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and it has performance advantages over more complicated algorithms in certain situations, particularly where auxiliary memory is limited.


Complexity
| Name | Best | Average | Worst | Memory | Stable | Comments |
|---|---|---|---|---|---|---|
| Selection sort | n2 | n2 | n2 | 1 | No |
References
Implementations
-
1
# TODO: Implement in Python -
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
import org.algorithm_visualizer.*; import java.util.Arrays; public class Main { private static ChartTracer chartTracer = new ChartTracer(); private static LogTracer logTracer = new LogTracer("Console"); private static Integer [] array = (Integer[]) new Randomize.Array1D(15, new Randomize.Integer(1, 20)).create(); public static void main(String[] args) { int length = array.length; Layout.setRoot(new VerticalLayout(new Commander[]{chartTracer, logTracer})); logTracer.printf("original array = %s\n", Arrays.toString(array)); chartTracer.set(array); Tracer.delay(); int minIndex; for (int i = 0; i < length; i++) { chartTracer.select(i); Tracer.delay(); minIndex = i; for (int j = i + 1; j < length; j++){ chartTracer.select(j); Tracer.delay(); if(array[j] < array[minIndex]) { chartTracer.patch(j, array[j]); Tracer.delay(); chartTracer.depatch(j); minIndex = j; } chartTracer.deselect(j); } swap(minIndex, i, array); chartTracer.deselect(i); } logTracer.printf("sorted array = %s\n", Arrays.toString(array)); } private static void swap(int x, int y, Integer[] array) { int temp = array[x]; array[x] = array[y]; array[y] = temp; chartTracer.patch(x, array[x]); chartTracer.patch(y, array[y]); Tracer.delay(); chartTracer.depatch(x); chartTracer.depatch(y); } }
-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
console.log(`original array = [${D.join(', ')}]`); for (let i = 0; i < D.length - 1; i++) { let minJ = i; for (let j = i + 1; j < D.length; j++) { if (D[j] < D[minJ]) { minJ = j; } } if (minJ !== i) { console.log(`swap ${D[i]} and ${D[minJ]}`); const temp = D[i]; D[i] = D[minJ]; D[minJ] = temp; } } console.log(`sorted array = [${D.join(', ')}]`);