凛冬之翼---二分查找

昨天体侧来着,今天睡了一个好觉,下午来理学楼开始写代码,精神状态很好,争取多写几个poject哦!

题目:L是用户传入的一个线性表,其中ElementType元素可以通过>、==、<进行比较,并且题目保证传入的数据是递增有序的。函数BinarySearch要查找X在Data中的位置,即数组下标(注意:元素从下标1开始存储)。找到则返回下标,否则返回一个特殊的失败标记NotFound。
具体题目百度关键字:01-复杂度3 二分查找

解题思路:主要是一般二分查找的思路,但是要注意在while循环的时候循环次数的取值一般区(N/2)N是总数。

遇到的问题:1.在for()后面多打了一个;号导致的错误很难找到。
2.在运行代码的时候电脑管家自作聪明的把我的代码当作木马病毒给清除了,真是傻,以后再运行的时候记得
关掉电脑管家。
3.提交的是代码片段和我自己写的代码数据结构有所不同,注意更改格式。

代码:

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

#define MAXSIZE 10
#define NotFound 0
typedef int ElementType;

typedef int Position;
typedef struct LNode *List;
struct LNode {
    ElementType Data[MAXSIZE];
    Position Last; /* 保存线性表中最后一个元素的位置 */
};

List ReadInput(); /* 裁判实现,细节不表。元素从下标1开始存储 */
Position BinarySearch( List L, ElementType X );

int main()
{
    List L;
    ElementType X;
    Position P;

    L = ReadInput();
//    printf("%d",L->Last);
//    printf("%d",L->Data[L->Last]);
    scanf("%d", &X);
    P = BinarySearch( L, X );
    printf("%d\n", P);

    return 0;
}

List ReadInput(){
    int x,i;
    List p=(List)malloc(sizeof(LNode));
    scanf("%d",&x);
    getchar();
    for(i=0;i<x;i++){
    	scanf("%d",&p->Data[i]);
	}
	p->Last=x-1;
	return p;
} 
Position BinarySearch( List L, ElementType X ){
	int num,mid,first,last,p=-1;
	first=0;
	last=L->Last;
//	printf("%d",last); 
    num=last/2;
	while(num--){
		mid=(first+last)/2;
//		printf("%d",mid);
        if(L->Data[first]==X){
        	p=first;
        	break;
		}
		if(L->Data[last]==X){
			p=last;
			break;
		}
		if(L->Data[mid]==X){
		p=mid;
		break;
		
		}
		
		if(L->Data[mid]>X){
			last=mid;
		}
		if(L->Data[mid]<X){
			first=mid;
		}
	
	}
   if(p==-1)
   return NotFound;
   else
   return p+1;	
}

猜你喜欢

转载自blog.csdn.net/weixin_39042981/article/details/83475315