[출처 : http://inthechaos.tistory.com/entry/탐색-SearchMainc]
#pragma warning(disable:4996) #include <stdio.h> #include <stdlib.h> #include "Search.h" //상수 정의 enum { ARRAY_SIZE = 100, MAX_VALUE = 1000 }; void fillArray(int *array, int size); void printArray(const int *array, int size); int compare(const void *p1, const void *p2); void main(void) { int array[ARRAY_SIZE]; int value, pos; fillArray(array, ARRAY_SIZE); printArray(array, ARRAY_SIZE); //순차 탐색 printf("[순차 탐색]\n"); while(1) { printf("입력 : "); scanf("%d", &value); if(value < 0 || value >= MAX_VALUE) { break; } pos = linearSearch(array, ARRAY_SIZE, value); printf("결과 : %s\n\n", (pos != -1) ? "성공" : "실패"); } printf("\n\n"); //정렬 qsort(array, ARRAY_SIZE, sizeof(array[0]), compare); printArray(array, ARRAY_SIZE); //이진 탐색 printf("[이진 탐색]\n"); while(1) { printf("입력 : "); scanf("%d", &value); if(value < 0 || value >= MAX_VALUE) { break; } pos = linearSearchSort(array, ARRAY_SIZE, value); printf("순차 : %s\n\n", (pos != -1) ? "성공" : "실패"); pos = binarySearch(array, ARRAY_SIZE, value); printf("이진 : %s\n\n", (pos != -1) ? "성공" : "실패"); } } void fillArray(int *array, int size) { int i; for(i=0; i<size; i++) { array[i] = rand() % MAX_VALUE; } } void printArray(const int *array, int size) { int i; for(i=0; i<size; i++) { printf("%3d ", array[i]); if(i%10 == 9) { printf("\n"); } } printf("\n\n"); } int compare(const void *p1, const void *p2) { return *(int*) p1 - *(int*) p2; }