從您提供的代碼片段中,我假設您正在嘗試分別對矩陣的每一行進行排序。我注意到的第一件事是在矩陣的列(第二索引)的內存分配中存在拼寫錯誤。一個numRow行 X 爲numColumns矩陣的
合適的內存分配情況如下:
/* loop counter */
int i;
/* dynamic array sizes */
const int numRow = 5;
const int numColumns = 25;
/* allocate the row pointers */
int **dynamic2d = (int **)malloc(numRow * sizeof(int *));
/* for each row pointer */
for(i = 0; i < numRow; i++)
{
/* allocate columns */
dynamic2d[i] = (int *)malloc(numColumns * sizeof(int));
}
接下來你將不能夠簡單地調用的qsort(..)方法只有一次。該方法需要一個「平坦」或一維數組。您需要分別爲矩陣的每一行調用qsort(...)方法。這是演示如下:
/* sort array */
for(i = 0; i < numRow; i++)
qsort(dynamic2d[i], numElements, sizeof(int *), comp);
最後,你犯了一個比較方法的錯誤。此方法有嚴格的規則,需要遵循以正確工作。當前specifications說,「如果第一個參數分別小於,等於或大於第二個參數,應用程序應確保該函數返回小於,等於或大於0的整數如果兩個成員比較相同,它們在排序陣列中的順序是未指定的「
這是一個簡單的修復。簡單地編寫邏輯來產生如下所示的結果:
int comp(const void* firstArg, const void* secondArg)
{
/* get the values of the arguments */
int first = *(int *)firstArg;
int second = *(int *)secondArg;
/* return the value as expected by the qsort() method */
if(first < second)
{
return 1;
}
else if(second < first)
{
return -1;
}
return 0;
}
最後要注意的是,這將排序最大至至少。
如果您希望最小,請勿在比較器中切換邏輯。排序不會返回準確的結果。正確的方法是從後向前讀取陣列,如下所示:
您可以交換比較器中的參數以更改排序順序或從後向前讀取結果。
int comp(const void* firstArg, const void* secondArg)
{
/* get the values of the arguments */
int first = *(int *)secondArg;
int second = *(int *)firstArg;
...
}
或
/* print greatest to smallest */
for(i = 0; i < numRow; i++)
{
/* start at front and work to back */
for(j = 0; j < numColumns; j++)
printf("%d ", dynamic2d[i][j]);
printf("\n");
}
/* print smallest to greatest */
for(i = 0; i < numRow; i++)
{
/* start at back and work to front */
for(j = numColumns- 1; j >= 0; j--)
printf("%d ", dynamic2d[i][j]);
printf("\n");
}
希望這有助於!如果你需要將整個矩陣作爲一個整體進行排序......這是一個不同的野獸。
你的'comp'函數是錯誤的。如果'a'是最小可能的整數值而'b'是1呢?那麼'a - b'將是整數運算中最大可能的整數值(在大多數系統中),即使'comp'的結果應該是負值,這也是正值。 – 2012-03-12 19:19:54
三個整數是單個大值嗎? (即如果int是32位,它是一個96位數) – Skizz 2012-03-12 19:22:36
3最初表示第二維內的3個空格,就像第1行有3個值。 – 2012-03-12 19:26:49