Insertion sort is an algorithm of sorting an array whereby elements are compared against and inserted towards the left position.
The insertion sort (ascending to descending) code in C#:
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 | using System; class Program { static void Main(string[] args) { int [] array = new int [10] {100, 50, 20, 40, 10, 60, 80, 70, 90, 30}; int array_size = 10; Console.WriteLine("The array before Insertion Sort is: "); for (int i = 0; i < array_size; i++){ Console.WriteLine("array[" +i +"] = " +array[i]); } // Now we will use Insertion sort int temp, k; for (int i = 1; i < array_size; i++) { temp = array[i]; k = i - 1; while (k >= 0 && array[k] > temp) { array[k + 1] = array[k]; k--; } array[k + 1] = temp; } Console.WriteLine(); Console.WriteLine("The array after Insertion Sort is: "); for (int i = 0; i < array_size; i++) { Console.WriteLine("array[" + i + "] = " + array[i]); } } } |
Here is a dancing video that illustrates insertion sort:














