Sorts an array of data using the insertion sort algorithm : Sort « Collections Data Structure « C# / C Sharp






Sorts an array of data using the insertion sort algorithm

Sorts an array of data using the insertion sort algorithm
  

using System;

public class InsertionSort {
    
  public static void InsertNext(int i, int[] item) {
    int current = item[i];
    int j = 0;
    while (current > item[j]) j++;
    for (int k = i; k > j; k--)
      item[k] = item[k-1];
    item[j] = current;
  }

  public static void Sort(int[] item) {
    for (int i = 1; i < item.Length; i++) {
      InsertNext(i, item); 
    }
  }

  public static void Main()  {
    int[] item = new int[]{2,4,1,6,3,8,1,0,2,6,3,6};
    Sort(item);
    for(int i=0; i<item.Length;i++){
        Console.WriteLine(item[i]);
    }
  }
}

           
         
    
  








Related examples in the same category

1.Implements the recursive merge sort algorithm to sort an arrayImplements the recursive merge sort algorithm to sort an array
2.Bubble sortBubble sort
3.A simple version of the QuicksortA simple version of the Quicksort
4.Demonstrate the Bubble sortDemonstrate the Bubble sort
5.Insert Sort
6.A simple stable sorting routine - far from being efficient, only for small collections.
7.Quick Sort