I'm newbie in C#, and I've been doing algorithm about Shell Sort in C#.
This is my code
static void shellSort(int[] group, int[] h)
{
int step, i, j, x, len, n, k;
n = group.Length;
k = h.Length;
for (step = 0; step < k; step++)
{
len = h[step];
for (i = len; i < n; i++)
{
x = group[i];
j = i - len;
while ((x < group[j]) && (j >= 0)) // <--- Error here "Make sure the index is not a ngative number"
{
group[j + len] = group[j];
j = j - len;
}
group[j + len] = x;
}
}
}
static void Main(string[] args)
{
int[] group, h;
group = new int[8]{6, 7, 15, 8, 18, 25, 4, 0}
h = new int[3] { 5, 3, 1};
shellSort(group,h);
Console.ReadLine();
}
I did it follow this code that make from C:
void ShellSort(int a[], int N, int h[], int k)
{
int step,i,j,x,len;
for (step = 0 ; step
len = h[step];
for (i = len; i
x = a[i];
j = i-len;
while ((x=0))
{
a[j+len] = a[j];
j = j - len;
}
a[j+len] = x;
}
}
}
In C, this code have processed successfull. But in C#, i've got a error: "Make sure the index is not a ngative number" at while ((x < group[j]) && (j >= 0)) . But, I didn't repair it.
How could i repair it ? :(
Please help me.
Thank you in advance.
VulpesPosted Apr 3, 2011, 10:58 AM
Consequently, this line won't give an error even if j is negative:
while ((x=0))
This doesn't matter here because j has to be non-negative for the while loop to proceed.
However, C# is a safe language and array bounds are always checked (except in unsafe code). The easy fix here is to simply reverse the order of the operands:
while ((j >= 0) && (x < group[j]))
As long as j is non-negative, the second expression isn't evaluated and so it works fine.