Insertion Sort Algorithm in C# (Simple)
class InsertionSort
{
public static List<int> Execute(List<int> list)
{
//Iterate through entire list starting from 1
for (int i=1;i<list.Count;i++)
{
var index = i;
//Get current item from list.
var current = list[i];
//While previous is greater than current
while (index > 0 && list[index - 1] > current)
{
//Swap
list[index] = list[index - 1];
//Go back
index--;
}
//The current item is stored at the right position in the list.
list[index] = current;
}
return list;
}
}
{
public static List<int> Execute(List<int> list)
{
//Iterate through entire list starting from 1
for (int i=1;i<list.Count;i++)
{
var index = i;
//Get current item from list.
var current = list[i];
//While previous is greater than current
while (index > 0 && list[index - 1] > current)
{
//Swap
list[index] = list[index - 1];
//Go back
index--;
}
//The current item is stored at the right position in the list.
list[index] = current;
}
return list;
}
}
Comments
Post a Comment