This C# program demonstrates a simple implementation of the insert sort algorithm. Insert sort is a sorting algorithm that works by iterating through the elements of an array and inserting each element into its correct position in a sorted subarray.
The program has a Main
method and a insertsort
method. The Main
method creates an array of integers and prints it to the console. It then calls the insertsort
method and passes the array and its length as arguments.
The insertsort
method uses a nested loop to iterate through the elements of the array and insert each element into its correct position in a sorted subarray. It does this by comparing each element to the elements that come before it, and moving the element to the right until it finds its correct position.
Finally, the Main
method prints the sorted array to the console. The output of this program will be the original array followed by the sorted array.
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 | 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; } } } } } |