forum

Home / DeveloperSection / Forums / How do I set negative number to index of array in c#.

How do I set negative number to index of array in c#.

James Smith 5339 16-Apr-2011

Hi......

I had made a program in c# for shell sorting. When I write this code in c++ then it does not generate any error and sorting is completed but when I run this program in c# then I got an exception that index should not be begative in c++. I want to know that is it possible to make index as negative in c# or I had did any other mistake.
My C# version program is as follows.

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 had taken tis logic from c code which is as follows.

void ShellSort(int a[], int N, int h[], int k)
{
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;
}
}
}

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 ?


c# c# 
Updated on 16-Apr-2011

Can you answer this question?


Answer

1 Answers

Liked By