我已经采用 QuickSort 方法对数组的行进行排序。 这是代码:
这个很好用
static void QuickSort(int lowBound, int highBound, int[] a)
{
int temp = 0;
int x = random.Next(lowBound, highBound);
int pivot = a[x];
int i = lowBound;
int j = highBound;
do
{
while (a[i] < pivot) i++;
while (pivot < a[j]) j--;
if (i <= j)
{
temp = a[i]; //changes an element smaller than the pivot...
a[i] = a[j];//... with the greater one
a[j] = temp;
i++; j--;
}
}
while (i <= j);
if (lowBound < j) { QuickSort(lowBound, j, a); }//recursion
if (i < highBound){ QuickSort(i,highBound, a); }
}
这是有问题的方法
static void QuickSortMatrix(int[,] a)
{
int n = a.GetLength(0);
int m = a.GetLength(1);
for (int i = 0; i < n; i++)
{
QuickSortRow(0, m - 1, i, a);
}
for (int j = 0; j < m; j++)
{
QuickSortRow(0, n - 1, j, a);
}
}
static void QuickSortRow(int lowBound, int highBound, int row, int[,] a)
{
int temp = 0;
int x = random.Next(lowBound, highBound);
int pivot = a[row,x];
int p = lowBound;
int q = highBound;
do
{
while (a[row,p] < pivot) p++;
while (pivot < a[row,q]) q--;
if (p <= q)
{
temp = a[row,p];
a[row,p] = a[row,q];
a[row,q] = temp;
p++; q--;
}
}
while (p <= q);
if (lowBound < q) { QuickSortRow(lowBound, q, row, a); }
if (p < highBound) { QuickSortRow(p, highBound,row, a); }
}
起初,当执行“for”循环时,一切正常,但由于某种原因,当递归执行时,调用该方法时应该保持不变的行超出了矩阵边界。 这是我的数组,行数达到 4
int[,] matrix =
{
{7,8,9,10,11,5},
{3,6,4,16,22,4},
{7,9,17,8,3,21},
{24,7,11,19,3,4}
};
我希望我的解释足够清楚。
有人可以给我建议吗?我在这里缺少什么?
感谢您的热心帮助!
BR 斯蒂芬
最佳答案
n是矩阵(4)中的行数
m是矩阵(6)的列数
在您的第二个循环中,您将使用 0..m 并将该值传递给 row 参数。它爆炸了,因为矩阵中的列数多于行数。即它尝试读取矩阵 [4, 0]。
注意:据我所知,您不需要第二个循环,因为您的行已经在第一个循环之后排序。删除它,它不会抛出异常。
关于c# - Matrix Row - QuickSort递归问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4610296/