I am converting a C++ program to CSharp program. While C++ and Csharp are exactly the same, the C++ program runs with no problem for input { 5, 4, 1, 3, 6, 7, 2 } while in Csharp, there is index out of bound exception. I have pasted both the codes below and they are exactly the copy of each other but I cannot understand why there is an exception in CSharp version while C++ runs fine.
C++ Program
#include <iostream>
using namespace std;
#include <stdio.h>
#include<stdlib.h>
void swap (int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int partition (int A[], int l, int h)
{
int pivot = A[l];
int i = l, j = h;
do
{
do
{
i++;
} while (A[i] <= pivot);
do
{
j--;
} while (A[j] > pivot);
if (i < j)
swap (&A[i], &A[j]);
}
while (i < j);
swap (&A[l], &A[j]);
return j;
}
void QuickSort (int A[], int l, int h)
{
int j;
if (l < h)
{
j = partition (A, l, h);
QuickSort (A, l, j);
QuickSort (A, j + 1, h);
}
}
int main ()
{
int A[] = { 5, 4, 1, 3, 6, 7, 2 }, n = 7, i;
QuickSort (A, 0, n);
for (i = 0; i < 7; i++)
printf ("%d ", A[i]);
printf ("\n");
return 0;
}
CSharp Program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyApp
{
public class QuickSort2
{
int partition(int[] A, int l, int h)
{
int pivot = A[l];
int i = l, j = h;
do
{
do
{
i++;
}
while (A[i] <= pivot);
do
{
j--;
}
while (A[j] > pivot);
if (i < j)
Swap(ref A[i], ref A[j]);
}
while (i < j);
Swap(ref A[l], ref A[j]);
return j;
}
public void QuickSort(int[] A, int l, int h)
{
int j;
if (l < h)
{
j = partition(A, l, h);
QuickSort(A, l, j);
QuickSort(A, j + 1, h);
}
}
public void Swap(ref int x, ref int y)
{
int tmp = x;
x = y;
y = tmp;
}
}
}
[Test]
public void TestQuickSort2()
{
QuickSort2 quick = new QuickSort2();
int[] list = new int[] { 5, 4, 1, 3, 6, 7, 2};
quick.QuickSort(list, 0, 7);
for (int i = 0; i < 7; i++)
{
Console.Write(list[i] + " --> ");
}
}
Edit 2. The problem happens at the following location and iteration