데이터 구조 - 찾기 (기본)

/*
1.           :(n+1)/2
2.                     O(logn)
*/
#include<stdio.h>

using namespace std;

#define MAX_NUM 5
typedef struct {
    int key;
}EleType;
/*    */
int seqsearch(EleType arr[], int searchNum, int n) {
    int i;
    arr[n].key = searchNum;
    for(i = 0; arr[i].key != searchNum; i++) {
        ;
    }
    return (( i<n ) ? i : -1);
}
/*    */
int binsearch(EleType arr[], int searchNum, int n) {
    int left = 0;
    int right = n-1;
    int middle;
    while(left<right) {
        middle = (left+right)/2;
        if(searchNum > arr[middle].key) left = middle + 1;
        else if(searchNum < arr[middle].key) right = middle - 1;
        else return middle;
    }
}
int main() {
    EleType arr[MAX_NUM];
    for(int i = 0; i<MAX_NUM; i++) {
        arr[i].key = 2*i;
    }
    int n=0;
    for(int i = 0; i<MAX_NUM; i++) {
		printf("     %d   :%d
",2*i,seqsearch(arr,2*i,MAX_NUM)); printf(" %d :%d
",2*i,binsearch(arr,2*i,MAX_NUM)); } return 0; }

좋은 웹페이지 즐겨찾기