Reputation: 31
I am trying to use insertion sort to sort an array. However, when applying it, it does not include the first element of the array in the ranking. What could be the reason?
Here is my code below:
namespace InsertionSort
{
class Program
{
static void Main(string[] args)
{
int min = 0, max = 40;
int[] array1 = new int[10];
Random randNum = new Random();
for (int i = 0; i < array1.Length; i++)
{
array1[i] = randNum.Next(min, max);
}
foreach (var item in array1)
{
Console.WriteLine(item);
}
Console.WriteLine("***************");
for (int j = 1; j < array1.Length; j++)
{
int key,i;
key = array1[j];
i = j - 1;
while ((i>0)&&array1[i]>key )
{
array1[i + 1] = array1[i];
i = i - 1;
}
array1[i + 1] = key;
}
foreach (var item in array1)
{
Console.WriteLine(item);
}
}
}
}
Upvotes: 1
Views: 44
Reputation: 147
while ((i>0)&&array1[i]>key )
You probably want to have i>=0
instead of i>0
, so the inner loop could actually reach the first element at index 0
.
Upvotes: 2