[英]Sort an array of structures in alphabetical order using merge sort
所以基本上我創建了 2 個結構:一個叫做product
,另一個叫做order
。 一個訂單有一個產品數組,每個產品都有一個字符串描述。
我正在嘗試按字母順序按名為set_prod
的順序對一系列產品進行排序,我需要根據產品描述對其進行排序。
為此,我找到了一個合並排序算法,但當我嘗試對其進行調整以對我的結構進行排序時,它會出現分段錯誤(核心轉儲)錯誤和其他我不理解的錯誤。
這是代碼:
typedef struct product {
int ident;
char desc[MAX_CHARS]; /* string that describes a product eg. "bread" */
int price; /* price of the product*/
int weight; /* weight of the product eg. 2kg */
int quant; /* quantity of the product in stock */
int state_prod;
} product;
typedef struct order {
int ident_o;
product set_prod[MAX_PRODS_OD]; /* Set of products */
int state;
} order;
void Merge_str_2(product *arr[], int low, int mid, int high) //Merging the Array Function
{
int nL = mid - low + 1;
int nR = high - mid;
char **L = malloc(sizeof(char *) * nL);
char **R = malloc(sizeof(char *) * nR);
int i;
for (i = 0; i < nL; i++) {
L[i] = malloc(sizeof(arr[low + i]->desc));
strcpy(L[i], arr[low + i]->desc);
}
for (i = 0; i < nR; i++) {
R[i] = malloc(sizeof(arr[mid + i + 1]->desc));
strcpy(R[i], arr[mid + i + 1]->desc);
}
int j = 0, k;
i = 0;
k = low;
while (i < nL && j < nR) {
if (strcmp(L[i], R[j]) < 0)
strcpy(arr[k++]->desc, L[i++]);
else
strcpy(arr[k++]->desc, R[j++]);
}
while (i < nL)
strcpy(arr[k++]->desc, L[i++]);
while (j < nR)
strcpy(arr[k++]->desc, R[j++]);
}
void MergeSort_str(product **arr[], int low, int high) //Main MergeSort function
{
if (low < high) {
int mid = (low + high) / 2;
MergeSort_str(arr, low, mid);
MergeSort_str(arr, mid + 1, high);
Merge_str_2(arr, low, mid, high);
}
}
我只能使用gcc -Wall -Wextra -Werror -ansi -pedantic
編譯,並且收到以下警告:
In function ‘main’:
warning: passing argument 1 of ‘MergeSort_str’ from incompatible pointer type [-Wincompatible-pointer-types]
MergeSort_str(sistem_orders[ide].set_prod,0,MAX_PRODS_OD-1);
^~~~~~~~~~~~~
note: expected ‘product *** {aka struct product ***}’ but argument is of type ‘product * {aka struct product *}’
void MergeSort_str(product** arr[],int low,int high);
^~~~~~~~~~~~~
In function ‘MergeSort_str’:
warning: passing argument 1 of ‘Merge_str_2’ from incompatible pointer type [-Wincompatible-pointer-types]
Merge_str_2(arr,low,mid,high);
^~~
note: expected ‘product ** {aka struct product **}’ but argument is of type ‘product *** {aka struct product ***}’
void Merge_str_2(product* arr[],int low,int mid,int high)
^~~~~~~~~~~
真的,任何幫助將不勝感激,因為我對這些錯誤一無所知。
問題是您的 sort 函數旨在對指針數組進行排序,而您想要對結構數組進行排序。 因此,您需要重寫 sort 函數以處理結構數組,或者創建一個指針數組並對其進行排序,然后將其轉換回(已排序的)結構數組。
最簡單的方法可能只是使用 stdlib qsort 函數(它執行快速排序,而不是歸並排序),該函數具有用於對任意對象數組進行排序的 API:
int product_compare(const void *a_, const void *b_) {
const product *a = a_;
const product *b = b_;
return strcmp(a->desc, b->desc); }
...在主要(或其他功能)中:
qsort(sistem_orders[ide].set_prod, MAX_PRODS_OD, sizeof(product), product_compare);
請注意,這會將空元素排序到數組的前面,這可能不是您想要的——您可能希望忽略空元素並將非空元素保留在前面,在這種情況下,您真的想擴展您的struct order
與產品數量的計數,並將該計數傳遞給 qsort 作為第二個參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.