Tuan 0

Tuan 0

  • NA
  • 1
  • 3.8k

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

Apr 3 2011 10:19 AM
Hello everybody,

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 <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 ? :(

Please help me.
Thank you in advance.

Answers (1)