Update 3.二分查找.cpp
原程序的main()中,list L 没有初始化是不可以直接使用的,在你的基础上进行了修改
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include "stdafx.h"
|
||||
#include<stdlib.h>
|
||||
|
||||
#define MAXSIZE 10
|
||||
#define NotFound 0
|
||||
@@ -7,39 +7,53 @@ typedef int ElementType;
|
||||
|
||||
typedef int Position;
|
||||
typedef struct LNode *List;
|
||||
struct LNode {
|
||||
ElementType Data[MAXSIZE];
|
||||
Position Last; /* 保存线性表中最后一个元素的位置 */
|
||||
struct LNode
|
||||
{
|
||||
ElementType Data[MAXSIZE];
|
||||
Position Last;/* 保存线性表中最后一个元素的位置 */
|
||||
};
|
||||
|
||||
Position BinarySearch( List L, ElementType X );
|
||||
List CreatList();//初始化链表
|
||||
Position BinarySearch(List L, ElementType X);
|
||||
|
||||
int main()
|
||||
List CreatList()
|
||||
{
|
||||
List L;
|
||||
ElementType X;
|
||||
Position P;
|
||||
|
||||
L->Data = int[]{1,3,5};
|
||||
L->Last = 3;
|
||||
scanf("%d", &X);
|
||||
P = BinarySearch( L, X );
|
||||
printf("%d\n", P);
|
||||
|
||||
return 0;
|
||||
List L;
|
||||
L = (List)malloc(sizeof(struct LNode));
|
||||
L->Last = NULL;
|
||||
return L;
|
||||
}
|
||||
|
||||
Position BinarySearch( List L, ElementType X ){
|
||||
Position BinarySearch(List L, ElementType X)
|
||||
{
|
||||
ElementType left = 1;
|
||||
ElementType right = L->Last;
|
||||
while(left<right){
|
||||
ElementType center = (left+right)/2; //先找中间值
|
||||
if(L->Data[center] < X){ //比中间值大,X 在右半边
|
||||
left = center+1;
|
||||
}else if(X < L->Data[center]){ //比中间值小,X 在左半边
|
||||
right = center-1;
|
||||
}else //找到了,直接返回
|
||||
while (left < right)
|
||||
{
|
||||
ElementType center = (left + right) / 2;
|
||||
if (L->Data[center] < X)
|
||||
left = center + 1;
|
||||
else if (X < L->Data[center])
|
||||
right = center - 1;
|
||||
else
|
||||
return center;
|
||||
}
|
||||
return NotFound;
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
List L;
|
||||
ElementType X;
|
||||
Position P;
|
||||
|
||||
L = CreatList();
|
||||
for (int i = 1; i < 4; i++)
|
||||
L->Data[i] = 2 * i - 1;
|
||||
L->Last = 3;
|
||||
scanf("%d", &X);
|
||||
P = BinarySearch(L, X);
|
||||
printf("%d\n", P);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user