Implementing Insertion Sort
Implementing the Insertion Sort algorithm in C#:
Implementing the Insertion Sort algorithm in C# involves iterating through an array, progressively building a sorted section at the beginning of the array. For each iteration, the current element is compared with the ones before it, moving each one step to the right until finding the correct position for the current element.
Here's a simple implementation of the Insertion Sort algorithm in C#:
using System; class InsertionSortExample { static void Main(string[] args) { int[] arr = { 64, 34, 25, 12, 22, 11, 90 }; Console.WriteLine("Original array:"); foreach (int i in arr) { Console.Write(i + " "); } Console.WriteLine(); InsertionSort(arr); Console.WriteLine("\nSorted array:"); foreach (int i in arr) { Console.Write(i + " "); } Console.ReadKey(); } static void InsertionSort(int[] arr) { int n = arr.Length; for (int i = 1; i < n; ++i) { int key = arr[i]; int j = i - 1; // Move elements of arr[0..i-1], that are greater than key, // to one position ahead of their current position while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } } }
This C# program defines a method InsertionSort
that takes an integer array as input and sorts it in ascending order using the Insertion Sort algorithm. The Main
method demonstrates how to use this sorting method with an example array. It prints out the array before and after sorting to show the effect of the algorithm.
Source Code:
Download
11 comments