[英]Using qsort with a define struct
我正在學習C並且正在解決此挑戰 ,我不打算將其提交給uva平台,我編寫此練習的原因是為了傾斜,也許不是解決問題的最佳方法,但是我我正在嘗試。
我在終端中打印的輸入如下:
4
3
20 30 40 50 30 40
Res: 2
4
20 30 10 10 30 20 40 50
Res: 4
3
10 30 20 20 30 10
Res: 2
4
10 10 20 30 40 50 39 51
Res: 3
每個輸入測試的答案都不正確,我相信原因是qsort函數。 我對如何使用結構使用qsort函數感到困惑,我在調用稱為數組的結構,然后是輸入的大小,然后使用sizeof(int),但是我是否需要使用int或sizeof結構,最后我叫我的比較功能。 我的代碼是:
#include <stdio.h>
#include <string.h>
struct Dolls{
int w;
int h;
}array[20005];
int cmp(struct Dolls a, struct Dolls b){
if(a.w==b.w){
return a.h < b.h;
}else{
return a.w > b.w;
}
}
int arr[20005];
int dp[20005];
int n;
int bSearch(int num, int k){
int low=1;
int high = k;
int mid;
while(low<= high){
mid = (low+high)/2;
if(num>=dp[mid]){
low=mid+1;
}else{
high=mid-1;
}
}
return low;
}
int res_dolls(){
int k=1;
int i,pos;
dp[i]=arr[1];
for(i=2;i<=n;i++){
if(arr[i]>=dp[k]){
dp[++k] = arr[i];
}else{
pos = bSearch(arr[i],k);
dp[pos] = arr[i];
}
}
return k;
}
int main(){
int t,j;
scanf("%d",&t);
while(t--){
memset(array,0,sizeof(array));
scanf("%d",&n);
for(j=1;j<=n;j++){
scanf("%d %d",&array[j].w, &array[j].h);
}
qsort(array,n,sizeof(int),cmp);
for(j=1;j<=n;j++){
arr[j] = array[j].h;
}
printf("%d\n",res_dolls());
}
return 0;
}
您的cmp
函數需要定義為int (*)(const void *, const void *)
才能用於qsort
。
您執行比較的方式也不正確。 在qsort的手冊頁中:
如果認為第一個參數分別小於,等於或大於第二個參數,則比較函數必須返回小於,等於或大於零的整數。 如果兩個成員比較相等,則它們在排序數組中的順序是不確定的。
您進行的比較將返回<
或>
運算符的結果,該結果為0或1。您需要顯式檢查每種情況並返回正確的值。
int cmp(const void *va, const void *vb){
const struct Dolls *a = va;
const struct Dolls *b = vb;
if(a->w > b->w) {
return 1;
} else if(a->w < b->w){
return -1;
} else if(a->h > b->h) {
return 1;
} else if(a->h < b->h){
return -1;
} else {
return 0;
}
}
至於對qsort
的調用,您需要給它一個數組元素的大小,即整個結構的大小,而不是子字段的大小:
qsort(array,n,sizeof(struct Dolls),cmp);
編輯:
修復了參數名稱錯誤。 還更改了執行排序的方式,以符合比較功能的行為方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.