951
技術社區[雲棲]
qsort實現排序算法
#include <stdio.h>
#include <stdlib.h>
#define MAX_SQUARE_COUNT 10
typedef struct tagSquare
{
int no; //編號
int length; //長
int width; //寬
}Square;
// 1.按照編號從小到大排序
// 2.對於編號相等的長方形,按照長方形的長排序;
// 3.如果編號和長都相同,按照長方形的寬排序;
// 4.如果編號、長、寬都相同,就隻保留一個長方形用於排序,刪除多餘的長方形;最後排好序按照指定格式顯示所有的長方形;
int Compare(const void *p, const void *q)
{
Square *lhs = (Square *)p;
Square *rhs = (Square *)q;
if (lhs->no != rhs->no) // 如果編號不同,按從小到大排序
{
return lhs->no - rhs->no > 0 ? 1 : -1;
}
else
{
// 編號相同,如果長度不同,按長度從小到大排序
if (lhs->length != rhs->length)
{
return lhs->length - rhs->length > 0 ? 1 : -1;
}
else
{
// 編號和長度都相同,如果寬不同,則按寬從小到大排序
if (lhs->width != rhs->width)
{
return lhs->width - rhs->width > 0 ? 1 : -1;
}
}
}
return 0;
}
int main()
{
int count; // 正方形的個數
int i, j;
Square s[MAX_SQUARE_COUNT];
int length, width;
scanf("%d", &count); // 讀入正方形的個數
for (i = 0; i < count; i++)
{
scanf("%d%d%d", &s[i].no, &length, &width);
s[i].length = length > width ? length : width; // 大的為長
s[i].width = length < width ? length : width; // 小的為寬
}
// 第一個參數 -- 數組首地址
// 第二個參數 -- 數組元素的個數,即數組長度
// 第三個參數 -- 一個數組元素的內存大小
// 第四個參數 -- 比較函數
qsort(s, count, sizeof(s[0]), Compare);
printf("%d %d %d\n", s[0].no, s[0].length, s[0].width);
for (i = 1; i < count; i++)
{
// 如果編號、長度、寬度不全相同,則輸出
if (!(s[i].no == s[i - 1].no && s[i].length == s[i - 1].length
&& s[i].width == s[i - 1].width))
{
printf("%d %d %d\n", s[i].no, s[i].length, s[i].width);
}
}
return 0;
}
最後更新:2017-04-03 18:52:05