The Array is : 83 12 3 34 60 The Sorted Array is : 3 12 34 60 83
Users Online
· Members Online: 0
· Total Members: 188
· Newest Member: meenachowdary055
Forum Threads
Latest Articles
Articles Hierarchy
C# Program to Implement Insertion Sort
C# Program to Implement Insertion Sort
This is a C# Program to perform insertion sort.
This C# Program Performs Insertion Sort.
Here it takes an element from the list and places it in the correct location in the list. This process is repeated until there are no more unsorted items in the list.
Here is source code of the C# Program to Perform Insertion Sort. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
/* * C# Program to Perform Insertion Sort */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int[] arr = new int[5] { 83, 12, 3, 34, 60 }; int i; Console.WriteLine("The Array is :"); for (i = 0; i < 5; i++) { Console.WriteLine(arr[i]); } insertsort(arr, 5); Console.WriteLine("The Sorted Array is :"); for (i = 0; i < 5; i++) Console.WriteLine(arr[i]); Console.ReadLine(); } static void insertsort(int[] data, int n) { int i, j; for (i = 1; i < n; i++) { int item = data[i]; int ins = 0; for (j = i - 1; j >= 0 && ins != 1; ) { if (item < data[j]) { data[j + 1] = data[j]; j--; data[j + 1] = item; } else ins = 1; } } } } }
This C# program is used to implement insertion sort. Using for loop we are entering the elements to be sorted. The insertion_sort() function is used to sort elements in ascending. The second element of an array is compared with the elements that appear before it, only first element in this case.
If the second element is smaller than first element, second element is inserted in the position of first element. After first step, first two elements of an array will be sorted. The third element of an array is compared with the elements that appear before it, first and second element.
If third element is smaller than first element, it is inserted in the position of first element. If third element is larger than first element but, smaller than second element, it is inserted in the position of second element.
If third element is larger than both the elements, it is kept in the position as it is. After second step, first three elements of an array will be sorted if there are n elements to be sorted. Then, this procedure is repeated n-1 times to get sorted list of array.