데이터 구조 - 이분 찾기

17020 단어 데이터 구조
#include 
#include 
#include
#include
#define MAXSIZE 100
#define NotFound 0

 typedef struct LNode {
	int Data[MAXSIZE];
	int Last; /*                 */
}Node;

Node* ReadInput(); //       
void SortList(Node *l);//        
void printfList(Node *l);//     
int BinarySearch(Node *l, int x);//      

int main()
{
	Node *L;
	int X;
	int P;
	L = ReadInput();
	printf("        :
"
); printfList(L); printf(" :"); scanf("%d", &X); P = BinarySearch(L, X); P=P-1; printf("%d :%d
"
,X ,P); return 0; } Node* ReadInput() { Node *l = (Node *)malloc(sizeof(Node)); printf(" :"); int len; scanf("%d", &len); if (len>MAXSIZE|| l == NULL) { return NULL; } srand((int)time(0)); l->Last = 0; printf(" ( ):
"
); for (int i = 0; i < len; i++) { // l->Data[i] = rand() % 100 + 1; scanf("%d",&l->Data[i]); l->Last++;// last } SortList(l); return l; } void SortList(Node *l) { // int temp; for (int i = 0; i <l->Last-1; i++) { for (int j = i; j < l->Last; j++) { if (l->Data[i]>l->Data[j]) { temp = l->Data[j]; l->Data[j] = l->Data[i]; l->Data[i] = temp; } } } } void printfList(Node *l) { int i = 1; while (i<=l->Last) { printf("%d ", l->Data[i - 1]); i++; } printf("
"
); } int BinarySearch(Node *l, int x) { int begin = 0; int end = l->Last-1; int mid = 0; if (end<begin) { return NotFound;// } while (begin<=end) { mid = begin + ((end - begin) / 2); if (l->Data[mid]==x) { return mid+1;// +1 } else if (l->Data[mid]>x) { end = mid - 1;// end = mid-1 } else { begin = mid + 1;// begin } } return NotFound; }

좋은 웹페이지 즐겨찾기