HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpModerate

Performing insertion sort in C#

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
performinginsertionsort

Problem

This is my code in C# for performing insertion sort:

static int[] performInsertionSort(int[] inputarray)
{
    for (int i = 0; i 0)
        {
            if (inputarray[j-1] > inputarray[j])
            {
                int temp = inputarray[j-1];
                inputarray[j - 1] = inputarray[j];
                inputarray[j] = temp;

            }
            j--;
        }
    }
    return inputarray;
}


Is there a way to optimize this code? Can I make further changes to it?

Solution

Your sorting logic is dependent upon the specific type.

"Separate your data representation from logic." you must take advantage of the generic to reuse the same component to sort any kind of object. In case of class you can specify comparer to sort the values.

Naming convention should be followed. i and j does not make sense and in c# standard method naming convetion should Pascal case , should not start with lowercase.

Rest logic looks good.

public static T[] PerformInsertionSort(T[] inputarray, Comparer comparer=null)
    {
        var equalityComparer = comparer ?? Comparer.Default;
        for (var counter = 0; counter  0)
            {
                if(equalityComparer.Compare(inputarray[index - 1],inputarray[index])>0)
                {
                    var temp = inputarray[index - 1];
                    inputarray[index - 1] = inputarray[index];
                    inputarray[index] = temp;
                }
                index--;
            }
        }
        return inputarray;
    }

Code Snippets

public static T[] PerformInsertionSort<T>(T[] inputarray, Comparer<T> comparer=null)
    {
        var equalityComparer = comparer ?? Comparer<T>.Default;
        for (var counter = 0; counter < inputarray.Length - 1; counter++)
        {
            var index = counter + 1;
            while (index > 0)
            {
                if(equalityComparer.Compare(inputarray[index - 1],inputarray[index])>0)
                {
                    var temp = inputarray[index - 1];
                    inputarray[index - 1] = inputarray[index];
                    inputarray[index] = temp;
                }
                index--;
            }
        }
        return inputarray;
    }

Context

StackExchange Code Review Q#59968, answer score: 11

Revisions (0)

No revisions yet.