출처 | https://www.acmicpc.net/problem/11651
2차원 평면 위의 점 N개가 주어진다. 좌표를 y좌표가 증가하는 순으로, y좌표가 같으면 x좌표가 증가하는 순서로 정렬한 다음 출력하는 프로그램을 작성하시오.
첫째 줄에 점의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에는 i번점의 위치 xi와 yi가 주어진다. (-100,000 ≤ xi, yi ≤ 100,000) 좌표는 항상 정수이고, 위치가 같은 두 점은 없다.
첫째 줄부터 N개의 줄에 점을 정렬한 결과를 출력한다.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int x;
int y;
}coord;
int compare(const void* first, const void* second)
{
coord* a = (coord*)first;
coord* b = (coord*)second;
if (a->y < b->y)
return -1;
else if (a->y > b->y)
return 1;
else
{
if (a->x < b->x)
return -1;
else
return 1;
}
return 0;
}
int main()
{
int i, n;
coord* list;
scanf("%d", &n);
list = (coord*)malloc(n * sizeof(coord));
for (i = 0; i < n; i++)
{
scanf(" %d %d", &list[i].x, &list[i].y);
}
qsort(list, n, sizeof(list[0]), compare);
for (i = 0; i < n; i++)
{
printf("%d %d\n", list[i].x, list[i].y);
}
return 0;
}
[2]런타임 초과용
//#include <stdio.h>
//#include <stdlib.h>
//
//typedef struct
//{
// int x;
// int y;
//
//}Code;
//
//
//
//int compare(const void* a, const void* b)
//{
// Code A = *(Code*)a;
// Code B = *(Code*)b;
//
// if (A.y > B.y)
// {
// return 1;
// }
//
// else if (A.y == B.y)
// {
// if (A.x > B.x)
// {
// return 1;
// }
// else
// {
// return -1;
// }
// }
// return -1;
//
//}
//
//
//int main()
//{
// int a;
//
// scanf_s("%d", &a);
//
// Code temp[50];
//
// for (int i = 0; i < a; i++)
// {
// scanf_s("%d %d", &temp[i].x, &temp[i].y);
// }
//
// qsort(temp, a, sizeof(Code), compare);
//
//
//
// for (int i = 0; i < a; i++)
// {
// printf("%d %d\n", temp[i].x, temp[i].y);
//
// }
//
//}
참고 사이트 | https://sedangdang.tistory.com/16