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
Improvements you could very easily make:
ShellSort
rather than shellSort
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?
IList<T>
IComparer<T>
, providing an overload which uses the default.Very little of this is actually sort-related - I haven't verified whether your code is actually a legitimate shell sort or not...