Search code examples
c#algorithmsortingdesign-patternsshellsort

What is the most elegant way of shell sorting (comb / diminishing increment sorting) in C#?


Is there a better way to shell sort using C#?

// array of integers to hold values
private int[] a = new int[100];

// number of elements in array
private int count;

// Shell Sort Algorithm
public void sortArray()
{
  int i, j, increment, temp;

  increment = 3;

  while( increment > 0 )
  {
    for( i=0; i < count; i++ )
    {
      j = i;
      temp = a[i];

      while( (j >= increment) && (a[j-increment] > temp) )
      {
        a[j] = a[j - increment];
        j = j - increment;
      }

      a[j] = temp;
    }

    if( increment/2 != 0 )
    {
      increment = increment/2;
    }
    else if( increment == 1 )
    {
      increment = 0;
    }
    else
    {
      increment = 1;
    }
  }
}

By the way, I'm wondering because I have some different examples of 'elegant' sorts in different languages (like bubble sorting in C# and F#), and I'm comparing them. In real life, I'd probably use the following most of the time in C#:

Array.Sort( object[] )

I don't care if these are 'academic' and non-pragmatic patterns. You can down-mod me into oblivion if you want :)

KA


Solution

  • Improvements you could very easily make:

    • Don't keep state in the object. This should be easy to do just with local variables.
    • Use conventional C# names like ShellSort rather than shellSort
    • Use meaningful names like count instead of x
    • Use the conditional operator, e.g.

      // This replaces your last 12 lines
      int halfIncrement = increment / 2;
      increment = halfIncrement != 0 ? halfIncrement : 1 - increment;
      
    • Make the code generic - why restrict yourself to integers?

    • Make your method take the data in question, and make it an IList<T>
    • Make the sort order arbitrary via an IComparer<T>, providing an overload which uses the default.
    • Declare variables as late as possible to reduce their scope and improve readability

    Very little of this is actually sort-related - I haven't verified whether your code is actually a legitimate shell sort or not...