BINARY SEARCH (이진탐색)

What is it?

  • Binary search(이진탐색). 많은 탐색기법 중 간단하고 속도가 빨라 자주 쓰이는 로직이다.
  • 배열을 계속 반으로 갈라 UP/DOWN을 하면서 (1/2)n개로 줄여가며 탐색한다.
  • 반드시 정렬된 배열에서만 사용할 수 있다.
  • Worst Case, 'O( logn )'
  • 너무 간단한 코드라 자세한 설명은 생략한다.



CODE

/************************************************ * BINARY SEARCH ****************************** * ********************************* binaryS.c **** * ***********************************************/ #include <stdio.h> /* Length of Array */ #define MAX_BUFF 5 /* Data which into Array */ typedef struct DATA { int mKey; // 키 int mValue; // 값 } DATA; /****************************** * * BINARY SEARCH by Recursive * * ***************************** */ int BinarySearch(struct DATA aSortedArray[], int aBegin, int aEnd, int aFind) { /* Arguments */ // aSortedArray[] : 정렬된 배열 // aBegin : 배열의 0번째 인덱스 // aEnd : 배열의 끝 인덱스 // aFind : 찾고자 하는 값 X /* Array's middle index */ int mMid = 0; /* Escape condition */ if ( aBegin > aEnd ) { return -1; } /* Declare mMid's value */ mMid = ( aBegin + aEnd ) / 2; /* If i find the value X, */ if ( aSortedArray[mMid].mValue == aFind ) { /* Return */ return mMid; } /* If arry[mid] > X */ else if ( aSortedArray[mMid].mValue > aFind ) { /* Recursive, aEnd is mMid-1 */ return BinarySearch( aSortedArray, aBegin, mMid-1, aFind ); } /* If arry[mid] < X */ else if ( aSortedArray[mMid].mValue < aFind ) { /* Recursive, aBegin is mMid+1 */ return BinarySearch( aSortedArray, mMid+1, aEnd, aFind ); } } /* MAIN FUNCTION */ int main() { /* declare an Array which has struct datas */ struct DATA arr[MAX_BUFF]; /* Variables */ int mFindValue = 0; // 입력받는 찾을 값 int mIndex = 0; // 찾은 값의 인덱스 int inputKey = 0; // 배열에 들어갈 입력받은 key값 int inputValue = 0; // 배열에 들어갈 입력받은 value값 printf("\nEnter the 5 KEYs and VALUEs which you want : \n"); printf("\n\n :::: WARNING : YOU MUST ENTER BY ORDER FOR VALUEs::::\n\n"); for(int i = 0; i < MAX_BUFF; i++) { /* Fill the Array with inputed values */ scanf("%d", &inputKey); scanf("%d", &inputValue); arr[i].mKey = inputKey; arr[i].mValue = inputValue; printf("KEY : %d VALUE : %d and\n", inputKey, inputValue); } printf("\n\nThen, current array's status is : \n\n"); printf("Keys : [ "); for(int i = 0; i < MAX_BUFF; i++) { printf("%d ", arr[i].mKey); } printf("]\n"); printf("VALUEs : [ "); for(int i = 0; i < MAX_BUFF; i++) { printf("%d ", arr[i].mValue); } printf("]\n\n\n"); while(mFindValue!=999) { printf("Enter the number which you wanna find (if you want to exit it, enter '999' : "); scanf("%d", &mFindValue); if(mFindValue==999) { printf("\n\nExit................\n\n"); break; } else { /* SEARCH */ mIndex = BinarySearch(arr, 0, MAX_BUFF-1, mFindValue); if(mIndex < 0) { printf("There is no %d in this array. \n\n", mFindValue); } else { printf("\n%d is in Array[ %d ] and %d's KEY is %d\n\n", mFindValue, mIndex, mFindValue, arr[mIndex].mKey); } } } return 0; }


블로그 이미지

차트

소소한 일상 C코드 DB 항상 행복하게^-^★

,

INSERTION SORT (삽입정렬)

What is it?

  • Insertion sort (삽입정렬), 많은 정렬 중 널리 쓰이는 정렬기법이다.
  • 정렬된 하위배열에 원소를 채워넣는 기법이다.
  • Worst Case, 'O( n2 )'
  • 간단한 코드지만, 부연 설명을 하자면
    • 값이 이미 채워져 있는 데이터 기반이 아닌, 값을 채울 때마다 바로바로 정렬되는 방식이다.
    • 리스트로 구현하는 원리와 비슷하다.


CODE

/************************************************* * INSERTION SORT ****************************** * **************************** insertionsort.c **** * ***********************************************/ #include <stdio.h> /* Length of Array */ #define MAX_BUFF 10 /* Declaring for functions */ void Initiation(int arr[]); // Initiation for Array void PrintArray(int arr[]); // Print Array void InsertionSort(int arr[], int InputValue); // Insertion Sort /* Global variable for counting */ int CountValues = 0; /* **************** * * MAIN FUNCTION * * **************** */ int main() { /* Variables */ int mInputValue = 0; // Input Value int mCountValue = 0; // Count int SortedArray[MAX_BUFF + 1]; // Array /* Initiation */ Initiation(SortedArray); printf("\n"); /* Enter the Input for the number of array's size */ while(mCountValue < MAX_BUFF) { printf("Enter the number which you wanna into an Arrary : "); scanf("%d", &mInputValue); CountValues++; mCountValue++; /* SORT */ InsertionSort(SortedArray, mInputValue); PrintArray(SortedArray); } printf("\n"); return 0; } /* Initiation function */ void Initiation(int arr[]) { int Index = 0; for ( Index = 0; Index < MAX_BUFF; Index++) { arr[Index] = '\0'; } } /* Print function */ void PrintArray(int arr[]) { int Index = 0; printf("\n[ "); for( Index = 0; Index < MAX_BUFF; Index++ ) { printf("%d ", arr[Index]); } printf("]\nThe number of Values : %d\n\n", CountValues); } /* ****************** * INSERTION SORT * * ***************** */ void InsertionSort(int arr[], int aInputValue) { /* Variables for FOR clauses */ int Seeing = 0; int Index = 0; for ( Seeing = 0; Seeing < CountValues; Seeing++ ) { /* If an Array is empty, */ if ( arr[Seeing] == '\0' ) { arr[Seeing] = aInputValue; } /* If Array[INDEX] > Input, */ if ( arr[Seeing] > aInputValue ) { /* Move 1 index on right all values which bigger than Input */ for ( Index = CountValues; Index > Seeing; Index-- ) { arr[Index] = arr[Index-1]; } arr[Seeing] = aInputValue; break; } // IF } // FOR }


블로그 이미지

차트

소소한 일상 C코드 DB 항상 행복하게^-^★

,

Array based QUEUE

What is it?

  • Array 기반의 Queue
  • 기본적으로 Enqueue (Insert)Dequeue (Delete) 연산이 가능한 FIFO (First-In, First-Out) 자료구조이다.
  • 너무 간단한 코드라 자세한 설명은 생략한다.
  • FIFO란? 먼저 들어온 자료가 먼저 나가는 것으로, 줄을 서다가 입장하는 것을 연상하면 된다.


CODE

/************************************************** * Array 기반의 Queue ***************************** * ************************************ q.c ******** * *************************************************/ #include <stdio.h> #define MAX_BUFF 10 /* Data for Queue */ typedef struct qData { int qkey; // 키 char qvalue; // 값 } qData; struct qData queue[MAX_BUFF]; /* Information for Queue */ int qTail; /* 삽입되는 부분에 대한 정보 */ int qNum; /* 입력받은 총 데이터 수 */ int countDe; /* 현재 데이터의 개수를 위한 디큐 횟수 */



/* * Dequeue시 Head의 데이터를 삭제하는 * 동시에 모든 데이터를 한칸씩 앞으로 * 옮긺으로써 Head를 따로 선언하지 않음. */

/* Queue Initiation */ void qInit() { qTail = 1; qNum = 0; countDe = 0; for(int i=0; i<MAX_BUFF; i++) { queue[i].qkey = '\0'; queue[i].qvalue = '\0'; } } /* Queue Print for Enqueue */ void qPrintEn() { int i; /* variable for 'for clause' */ printf("\n Current Queue's status is :\n\n"); printf(" KEY VALUE\n"); for( i = qTail-1 ; /*qTail-1*/ i >= 0; /*qHead-1*/ i--) { printf(" %d %s\n", queue[i].qkey, &queue[i].qvalue); } printf("\n"); printf("The number of data which you into : %d\n", qNum); printf("The number of data which current exist : %d\n\n", qNum-countDe); } /* Queue Print for Dequeue */ void qPrintDe() { int i; /* variable for 'for clause' */ printf("\n Current Queue's status is :\n\n"); printf(" KEY VALUE\n"); for( i = qTail-3 ; /* qTail-2 */ i>=0; /* qHead */ i--) { printf(" %d %s\n", queue[i].qkey, &queue[i].qvalue); } printf("\n"); printf("The number of data which you into : %d\n", qNum); printf("The number of data which current exist : %d\n\n", qNum-countDe); } /* Queue Insert the data 'val' */ void enQ(char val) { if ( qTail >= 11 ) { /* If the Queue is full */ printf("\nerror::queue overflow.\n"); } else { qNum++; queue[qTail-1].qkey = qNum; queue[qTail-1].qvalue = val; qPrintEn(); qTail++; } } /* Queue Delete the data from head */ void deQ() { if( qTail == 1 ) { /* If the Queue is empty */ printf("\nerror::queue is already empty.\n"); } else { countDe++; printf("Deleted data : %s\n", &queue[0].qvalue); queue[0].qkey = '\0'; queue[0].qvalue = '\0'; for(int i=1; i<qTail; i++) { queue[i-1].qkey = queue[i].qkey; queue[i-1].qvalue = queue[i].qvalue; } qPrintDe(); qTail--; } } /* MAIN FUNCTION */ int main() { qInit(); printf("\n\nIt's an array based Queue.\n\n"); int menu; char push; while(menu!=3) { printf("\nYou make a choice to menu.\n\n"); printf("Press '0' If you wanna Initiation.\n"); printf("Press '1' If you wanna Enqueue.\n"); printf("Press '2' Ifyou wanna Dequeue.\n"); printf("Press '3' If you wanna exit.\n\n"); printf(" PRESS : "); scanf("%d", &menu); switch(menu) { case 0: printf("You pressed '0' to Initiation.\n"); printf("So, the stack is cleared.\n"); qInit(); qPrintDe(); break; case 1: printf("You pressed '1' to Enqueue.\n"); printf("Press the character which you want to Enqueue. : "); scanf( "%s", &push ); enQ(push); break; case 2: printf("You pressed '2' to Dequeue.\n"); deQ(); break; case 3: printf("Exit......\n\n"); break; default: printf("It's wrong number. press again.\n\n"); break; } // switch } // while return 0; }


블로그 이미지

차트

소소한 일상 C코드 DB 항상 행복하게^-^★

,

Array based STACK

What is it?

  • Array 기반의 Stack
  • 기본적으로 Push (Insert)Pop (Delete)연산이 가능한 FILO (First-In Last-Out) 자료구조이다.
  • 너무 간단한 코드라 자세한 설명은 생략한다.
  • FILO란? 먼저 들어온 자료가 마지막에 나가는 것으로, 쌓아논 책을 위에서부터 습득하는 것을 연상하면 된다.



CODE

/**************************************************** * Array 기반의 STACK ******************************* * *********************************** st.c ********** * **************************************************/ #include<stdio.h> /* 배열의 크기를 상수로 지정 */ #define MAX_BUFF 10 /* 배열에 들어가는 데이터 */ typedef struct sData { int skey; //키 char svalue; //값 } sData; /* 크기가 MAX_BUFF인 스택 선언 */ struct sData stack[MAX_BUFF]; /* Information for Top of Stack */ int sTop; /* Information for number of datas */ int sNum; // 데이터가 들어온 총 횟수 int countPop; // 삭제연산의 수 /* Stack Initiation */ void sInit() { /* Top을 1로, 나머지는 모두 초기화한다 */ sTop = 1; sNum = 0; countPop = 0; for(int i=0; i<MAX_BUFF; i++) { stack[i].skey = '\0'; stack[i].svalue = '\0'; } } /**************************************************************** * Push 후 출력과 Pop 후 출력을 구별하는 게 좀 더 깔끔해서 구별함 * * ***************************************************************/ /* Stack Print for Push */ void sPrintPush() { printf("\n Current stack's status is :\n\n"); printf(" KEY VALUE\n"); for(int i=sTop-1; i>=0; i--) { printf(" %d %s\n", stack[i].skey, &stack[i].svalue); } printf("\n"); printf("The number of data which you into : %d\n", sNum); printf("The number of data which current exist : %d\n\n", sNum-countPop); } /* Stack Print for Pop */ void sPrintPop() { printf("\n Current stack's status is :\n\n"); printf(" KEY VALUE\n"); for(int i=sTop-2; i>=0; i--) { printf(" %d %s\n", stack[i].skey, &stack[i].svalue); } printf("\n"); printf("The number of data which you into : %d\n", sNum); printf("The number of data which current exist : %d\n\n", sNum-countPop); } /* Stack Insert the data 'val' */ void sPush(char val) { if(sTop-1>=MAX_BUFF) { /* If the STACK is full */ printf("\nerror::stack overflow.\n"); } else { sNum++; stack[sTop-1].skey = sNum; stack[sTop-1].svalue = val; sPrintPush(); sTop++; } } /* Stack Delete the data of top */ void sPop() { if(sTop-1==0) { /* If the STACK is empty */ printf("\nerror::stack is already empty.\n"); } else { sTop--; printf("Poped data : %s\n", &stack[sTop].svalue); stack[sTop-1].skey = '\0'; stack[sTop-1].svalue = '\0'; countPop++; sPrintPop(); } } /* MAIN FUNCTION */ int main() { sInit(); printf("\n\nIt's an array based STACK.\n\n"); int menu; char push; while(menu!=3) { printf("\nYou make a choice to menu.\n\n"); printf("Press '0' If you wanna Initiation.\n"); printf("Press '1' If you wanna push.\n"); printf("Press '2' Ifyou wanna pop.\n"); printf("Press '3' If you wanna exit.\n\n"); printf(" PRESS : "); scanf("%d", &menu); switch(menu) { case 0: printf("You pressed '0' to Initiation.\n"); printf("So, the stack is cleared.\n"); sInit(); sPrintPop(); break; case 1: printf("You pressed '1' to Push.\n"); printf("Press the character which you want to push. : "); scanf("%s", &push); sPush(push); break; case 2: printf("You pressed '2' to Pop.\n"); sPop(); break; case 3: printf("Exit......\n\n"); break; default: printf("It's wrong number. press again.\n\n"); break; } // switch } // while return 0; }


블로그 이미지

차트

소소한 일상 C코드 DB 항상 행복하게^-^★

,