qsort实现排序算法

来源:互联网 发布:ios 网络加载等待动画 编辑:程序博客网 时间:2024/05/18 07:05
#include <stdio.h>#include <stdlib.h>#define MAX_SQUARE_COUNT 10typedef 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;}