2013년 1월 23일 수요일

헤드 퍼스트 C 7강 (Qsort)


#include <stdio.h>
#include <string.h>
#include <stdlib.h>

//숫자 정렬(오름차순)
int compare_scores(const void* score_a, const void* score_b)
{
int a = *(int*)score_a;
int b = *(int*)score_b;
return a - b;
}

//숫자 정렬(내림차순)
int compare_scores_desc(const void* score_a, const void* score_b)
{
int a = *(int*)score_a;
int b = *(int*)score_b;
return b - a;
}

typedef struct {
int width;
int height;
} rectangle;

//사각형 크기 정렬(오름차순)
int compare_areas(const void* a, const void* b)
{
rectangle* ra = (rectangle*)a;
rectangle* rb = (rectangle*)b;
int area_a = (ra->width * ra->height);
int area_b = (rb->width * rb->height);
return area_a - area_b;
}

//글씨 정렬(오름차순)
int compare_names(const void* a, const void* b)
{
char** sa = (char**)a;
char** sb = (char**)b;
return strcmp(*sa, *sb);
}

//사각형 크기 정렬(내림차순)
int compare_areas_desc(const void* a, const void* b)
{
return compare_areas(b, a);
}

//이름 정렬 (내림차순)
int compare_names_desc(const void* a, const void* b)
{
return compare_names(b, a);
}

int main()
{
//선언부
int scores[] = { 543, 323, 32, 554, 11, 3, 112 };
int i;
char* names[] = { "카렌", "마크", "브렛", "몰리" };

//구현부
qsort(scores, 7, sizeof(int), compare_scores_desc);
puts("scores를 정렬한 결과:");
for (i=0; i<7; i++) {
printf("점수 = %i\n", scores[i]);
}


qsort(names, 4, sizeof(char*), compare_names);
puts("이름을 정렬한 결과:");
for (i=0; i<4; i++) {
printf("%s\n", names[i]);
}

return 0;
}

댓글 없음:

댓글 쓰기