阅读951 返回首页    go 阿里云 go 技术社区[云栖]


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

  上一篇:go ASP.NET 服务器参数、路径等
  下一篇:go 压缩解压缩文件(zip格式)