From your code:
static int[] performInsertionSort(int[] inputarray)
{
for (int i = 0; i < inputarray.Length-1; i++)
{
int j = i+1;
while (j>0)
{
if (inputarray[j-1] > inputarray[j])
{
int temp = inputarray[j-1];
inputarray[j - 1] = inputarray[j];
inputarray[j] = temp;
}
j--;
}
}
return inputarray;
}
I can see a couple of things that I would do differently.
Instead of using a while on the inside I would probably use another for
loop because it would look a little bit cleaner. I would also change the name of inputarray
to inputArray
because of common naming schemes.
Personally I think for something this simple i
and j
are fine, if the operations become more complex and you aren't just sorting random numbers, then you would have something meaningful that you could name them, so I would just keep i
and j
.
Here is what my version would look like:
static int[] performInsertionSort(int[] inputArray)
{
for (int i = 0; i < inputArray.Length-1; i++)
{
for (int j = i + 1; j > 0; j--)
{
if (inputArray[j-1] > inputArray[j])
{
int temp = inputArray[j-1];
inputArray[j-1] = inputArray[j];
inputArray[j] = temp;
}
}
}
return inputArray;
}
I wanted to test this to make sure that it worked correctly, here is my code with the output programmed into the application.
Insertion sort revised with output to console