# How do I set a negative number to index of array in C# ?

in C#
Hello everybody,

I'm newbie in C#, and I've been doing algorithm about Shell Sort in C#.

This is my code

[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();
}
[/CODE]

I did it follow this code that make from C:
void ShellSort(int a[], int N, int h[], int k)
[code]
{
int step,i,j,x,len;
for (step = 0 ; step <k; step ++)
{
len = h[step];
for (i = len; i <N; i++)
{
x = a[i];
j = i-len;
while ((x<a[j])&&(j>=0))
{
a[j+len] = a[j];
j = j - len;
}
a[j+len] = x;
}
}
}
[/code]

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.

## Comments

• You should change that line to:
while ((j >= 0) && (x < group[j]))

since it seems that the compiler checks the first condition first, and then you dont have to worry about the second one (j>=0 already says that if j is negative, don't continue).

Hope this helps you!
Sign In or Register to comment.

#### Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!