Insertion Sort Function
Our function will receive an array as the input.
The steps of insertion sort explained below:
- Looping from first until last index of array.
for (int i = 1; i < input.Length; i++)
{
}
- Create the temp variable to store the value of certain index, then create variable j to compare with previous value.
temp = input[i];
j = i - 1;
- If value of j less than i, move the j to temp, i to j, and temp to i.
- Check value of j with j-1, if j less than j-1, the method should repeat number 2.
while(j >= 0 && input[j] > input[j+1])
{
input[j+1] = input[j];
input[j] = temp;
j = j - 1;
}
- Keep looping until the end of array.
Final code:
static void insertionSort(int[] input)
{
int temp, j;
for (int i = 1; i < input.Length; i++)
{
temp = input[i];
j = i - 1;
while(j >= 0 && input[j] > input[j+1])
{
input[j+1] = input[j];
input[j] = temp;
j = j - 1;
}
}
foreach (var a in input)
Console.WriteLine(a);
}