소개글
[C언어] shell sort 프로그램에 대한 자료입니다.
목차
#define MAXMAJOR 9 /*전공의 최대 크기*/
#define MAXNAME 10 /*이름의 최대 크기*/
typedef struct _people { // 학생 자력이 입력될 변수.
char *major; // 전공
char *name; // 이름
double point; // 학점
} people;
people *Get_DataFromFile(char *s, int *cnt); // 파일로 부터 자료를 받아오는 함수.
people *Save_Data(people *t, people *s, int n); // 자료를 다른 변수로 옮기는 함수.
char *Get_major(char *t); // 전공을 저장하는 함수.
char *Get_name(char *t); // 이름을 저장하는 함수.
void print_Data(int *index, people *t, int n); // 자료를 출력하는 함수.
int double_cmp(const people a, const people b); // 학점을 비교하는 함수.
int str_cmp(const people a, const people b); // 이름을 비교하는 함수.
void shell_sort(int *index, people *base, int nelem, int (*fcmp)(const people, const people)); // 정렬 함수.
본문내용
int main(int argc, char *argv[])
{
int i, cnt = 0;
people *data;
int *index;
char *s = "infile.txt";
if(argc == 1) data = Get_DataFromFile(s, &cnt); // 프로그램 시작할 때 파일명을 안주면 infile 오픈.
else{
data = Get_DataFromFile(*++argv, &cnt); // 프로그램 시작시 입력한 파일명으로 자료 저장.
}
index = (int *)malloc(sizeof(int) * cnt); // 인덱스 배열 생성.
for(i = 0; i < cnt; i++) index[i] = i;
shell_sort(index, data, cnt, str_cmp); // 이름순으로 정렬.
print_Data(index, data, cnt); // 출력.
printf("\n\n");
shell_sort(index, data, cnt, double_cmp); // 학점순으로 정렬.
print_Data(index, data, cnt); // 출력.
printf("\n\n");
free(index);
return 1;
}
people *Get_DataFromFile(char *s, int *cnt)
{
///////////////////////////////////////////////////////////////////////////
/*파일로 부터 자료를 저장하는 함수. 동적으로 배열을 생성하여 자료를 입력. /
/ 입력하면서 자료의 개수를 함께 증가시켜준다. */
///////////////////////////////////////////////////////////////////////////
char strbuf[10];
people *temp, *data;
FILE *in;
in = fopen(s, "r"); // 파일 오픈.
if(!in) { printf("File not found.\n"); return 0; } // file이 없는 경우 오류처리.
temp = (people *)malloc(sizeof(people)); // 이전 자료를 저장할 변수.
while(fscanf(in, "%s", strbuf) != EOF) {
data = Save_Data(temp, data, *cnt); // 자료를 저장할 구조체를 선언하고 이전 자료 저장.
data[*cnt].major = Get_major(strbuf); // 전공 저장.
if(fscanf(in, "%s", strbuf) != EOF) { data[*cnt].name = Get_name(strbuf);} // 이름 저장.
if(fscanf(in, "%s", strbuf) != EOF) { data[*cnt].point = atof(strbuf);} // 학점 저장.
*cnt += 1; // 카운터 증가.
temp = Save_Data(data, temp, *cnt); // 이전 자료를 저장.
}
fclose(in);
free(temp);
return data;
}