출처 : https://www.acmicpc.net/problem/11650
2차원 평면 위의 점 N개가 주어진다. 좌표를 x좌표가 증가하는 순으로, x좌표가 같으면 y좌표가 증가하는 순서로 정렬한 다음 출력하는 프로그램을 작성하시오.
첫째 줄에 점의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에는 i번점의 위치 xi와 yi가 주어진다. (-100,000 ≤ xi, yi ≤ 100,000) 좌표는 항상 정수이고, 위치가 같은 두 점은 없다.
첫째 줄부터 N개의 줄에 점을 정렬한 결과를 출력한다.
#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.x > B.x)
{
return 1;
}
else if (A.x == B.x)
{
if (A.y > B.y)
{
return 1;
}
else
{
return -1;
}
}
return -1;
}
int main()
{
int a;
scanf("%d", &a);
Code temp[a];
for (int i = 0; i < a; i++)
{
scanf("%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);
}
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int x;
int y;
} coord; //coord형의 구조체 선언
int compare(const void *a, const void *b)
{
coord A = *(coord *)a; //coord형의 A로 입력받은 a를 사용할 수 있게한다.
coord B = *(coord *)b;
if (A.x > B.x) // 구조체의 x를 끌고와서 사용한다. 오름차순 정렬
return 1;
else if (A.x == B.x) // x좌표가 같다면,
{
if (A.y > B.y) // y좌표를 비교한다. 오름차순 정렬
return 1;
else
return -1; // 그게 아니라면 -1반환.
}
return -1; // A.x < B.x면 -1
}
int main()
{
int n, i;
scanf("%d", &n);
i = 0;
coord arr[n]; // 구조체형으로 배열을 선언한다.
while (i < n)
{
scanf("%d %d", &arr[i].x, &arr[i].y);
// 구조체배열로 arr[0]의 x값,y값 각각 설정하면서 간다.
i++;
}
qsort(arr, n, sizeof(coord), compare); // 퀵정렬 사용
i = 0;
while (i < n)
{
printf("%d %d\n", arr[i].x, arr[i].y); // 정렬된 배열 출력
i++;
}
}
구조체로 선언했기 때문에 가능하다.
Code temp[a]
for( i = 0; i < a; i++)
scanf_s("%d %d" , &temp[i].x
출처 | https://twpower.github.io/56-qsort-in-c 참고
추가적으로 좌표를 표현 하고, 구조체의 사용법 다시 한 번 복습하자.