merge sort using two params. by 설악이


인자 두개를 소팅 하는 방법을 구현해 보았습니다. 
a인자를 먼저 쏘팅하고 a인자가 같으면 b인자를 기준으로 했습니다. 


#include <stdio.h>
#include <memory.h>
typedef struct MY_DB{
int a;
int b;
}MY_DB;

MY_DB sorting_test[10000];
MY_DB sorting_buff[10000];

int sorting_count = 0;

void insert_db(int a, int b)
{
sorting_test[sorting_count].a = a;
sorting_test[sorting_count++].b = b;
}

void merge_sort(int l, int r)
{
int i = 0;
if(r - l <=0)
return;
int idx, mid, ll, lr;
mid = (l+r)/2;

merge_sort(l, mid);
merge_sort(mid+1, r);

idx = ll = l;
lr = mid+1;

for(i = l; i <=r; i++)
{
sorting_buff[i] = sorting_test[i];
}

while(ll <= mid && lr<=r)
{
if(sorting_buff[ll].a<sorting_buff[lr].a)
{
sorting_test[idx++] = sorting_buff[ll++];
}
else if(sorting_buff[ll].a>sorting_buff[lr].a)
{
sorting_test[idx++] = sorting_buff[lr++];
}else // a 같을 경우
{
if(sorting_buff[ll].b<=sorting_buff[lr].b)
{
sorting_test[idx++] = sorting_buff[ll++];
}
else if(sorting_buff[ll].b>sorting_buff[lr].b)
{
sorting_test[idx++] = sorting_buff[lr++];
}
}
}
while(ll<=mid)
{
sorting_test[idx++] = sorting_buff[ll++];
}

while(lr<=r)
{
sorting_test[idx++] = sorting_buff[lr++];
}
}

int main(int argc, char *argv[])
{
int i = 0;

memset(sorting_test, 0, sizeof(sorting_test));
memset(sorting_buff, 0, sizeof(sorting_buff));

insert_db(1,5);
insert_db(1,2);
insert_db(1,3);
insert_db(2,7);
insert_db(3,3);
insert_db(2,3);
insert_db(1,1);
insert_db(2,1);
insert_db(5,11);

printf("before original \n");
for( i = 0; i<sorting_count; i++ )
printf("[%d],(a,b)= (%d, %d)\n", i, sorting_test[i].a, sorting_test[i].b);

merge_sort(0, sorting_count-1);


printf("----after sorting----\n");
for( i = 0; i<sorting_count; i++ )
printf("[%d],(a,b)= (%d, %d)\n", i, sorting_test[i].a, sorting_test[i].b);
}

1 2 3 4 5 6 7 8 9 10 다음