Date:

Share:

# Insertion Sort in C# – Programming Empire

### Java Lists (with examples) | Code Underscored

This article explains C # income sorting. Another simple sorting algorithm is income sorting. Basically, this algorithm works by actually dividing the list into two parts. While, the first part belongs to the sorted list, the second part is not sorted. Furthermore, the algorithm selects an element from the unsorted part and puts it in the right place in the sorted part of the list.

### Example of sorting using income sorting

In order to demonstrate income sorting, let’s say we need to sort this list [9, 3, 2, 1, 5, 8]. Moreover, the sorted part contains only the first element. Whereas the unsorted part contains the rest of the elements. So, the green element belongs to the sorted part of the list. While, the red ones belong to the unsorted part.

[9, 3, 2, 1, 5, 8]. Initially, the algorithm compares element 3 to 9 and places it in the first position and passes component 9. So the sorted list has two elements [3, 9].

[3, 9, 2, 1, 5, 8]. Moreover, it puts element 2 in its proper place.

[2, 3, 9, 1, 5, 8]. It then compares element 1 to each element in the sorted part and places element 1 in the first position.

[1, 2, 3, 9, 5, 8]. Similarly, it takes 5 as the next element and compares it to 9. Again, he compares 5 to 3. Since it is greater than 3, then it places 5 after 3.

[1, 2, 3, 5, 9, 8]. Similarly, element 8 is placed before 9. Finally, the entire list is sorted.

[1, 2, 3, 5, 8, 9]

### Implementing income classification in C #

The following code shows Implementing income classification in C #. Here, the variable i in the InsertionSort () function represents the unsorted part. While, j represents an element in the sorted part.

``````using System;

namespace InsertionSort
{
class Program

static void Main(string[] args)

int[] myarray =  4, 1, 9, -13, 90, 56, 81, 34, -2, -15, 60, 88 ;
Console.WriteLine("Array before sorting...");
foreach (int x in myarray)
Console.Write(x + "  ");
Sort.InsertionSort(myarray);
Console.WriteLine("nArray after sorting...");
foreach (int x in myarray)
Console.Write(x + "  ");
Console.WriteLine();

class Sort

public static void InsertionSort(int[] a1)

int j, x;
for(int i=1;i<a1.Length;i++)

x = a1[i];
j = i - 1;
while((j>=0) && (a1[j]>x))

a1[j + 1] = a1[j];
j--;

a1[j + 1] = x;

}``````

Productivity

Source