欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

二分查找

程序员文章站 2022-05-08 19:12:44
...

二分查找

#include<stdio.h>
#include<stdlib.h>

typedef struct node {
	int element[10];
	int length;
}Lel;
//二分查找
int Lbinary(Lel L, int K) {	//K为设置的哨兵
	int left, mid, right;	
	left = 0;
	right = L.length;
	while (left <= right) {			
		mid = (left + right) / 2;	
		if (L.element[mid] > K)		right = mid - 1;
		else if (L.element[mid] < K)	left = mid + 1;
		else return mid;
	}
	return -1;
}

int main() {
	Lel L = { 1,2,3,4,5,6,7,8,9,10,9 };
	int a;
	a = Lbinary(L, 6);
	printf("%d",a);
	system("pause");
	return 0;
}