@【数据结构】(有序顺序表的折半查找)
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
using namespace std;
typedef struct
{
int data[MAX];
int last;
}List;
List *INIT()
{
List *L;
L = (List*)malloc(sizeof(List));
L->last = 0;
return L;
}
void insert(List *&L, int i, int x)
{
int j;
if (L->last == MAX - 1)
cout << "表满" << endl;
if (i<1 || i>L->last + 2)
cout << "位置输入错误" << endl;
for (j = L->last; j > i; j--) //位置i后的元素后移一位
L->data[j] = L->data[j - 1];
L->data[i - 1] = x;
L->last++;
}
void out(List *L)
{
int i;
for (i = 0; i < L->last; i++)
cout << L->data[i] << " ";
cout << endl;
}
int find(List *L, int x)
{
int mid,m,n;
m = 1; n = L->last;
while (m <= n)
{
mid = (m + n) / 2;
if (L->data[mid] == x)
return mid;
else if (L->data[mid] > x)
m = mid + 1;
else n = mid - 1;
}
return 0;
}
void main()
{
List *L;
L = INIT();
insert(L, 1, 2); insert(L, 2, 5);
insert(L, 3, 7); insert(L, 4, 8); insert(L, 5, 10);
cout << "有序表为:";
out(L);
cout << "请输入要查找的元素:";
int x;
cin >> x;
cout << "进行折半查找,元素位置为(从0开始计):"<< find(L,x)<<endl;
system("pause");
}
测试: