顺序查找
#include <iostream>
#define MAX 10
using namespace std;
typedef int ElemType;
typedef struct {
ElemType *elem;
int length;
} sqList;
void init(sqList &L) {
L.elem = new ElemType[MAX+1];
L.length = 0;
int e;
for(int i = 1; i <= MAX; i++) {
cin>>e;
L.elem[i] = e;
L.length++;
}
}
int search(sqList L, int e) {
L.elem[0] = e;
int i;
for(i = L.length; L.elem[i] != e; --i);
return i;
}
int main() {
sqList L;
init(L);
cout<<search(L, 18);
return 0;
}
折半查找
#include <iostream>
#define MAX 10
using namespace std;
typedef int ElemType;
typedef struct {
ElemType *elem;
int length;
} sqList;
void init(sqList &L) {
L.elem = new ElemType[MAX];
L.length = 0;
int e;
for(int i = 0; i < MAX; i++) {
cin>>e;
L.elem[i] = e;
L.length++;
}
}
void sort(sqList &L) {
for(int i = 1; i < L.length; i++)
for(int j = 0; j < L.length - i; j++)
if(L.elem[j] > L.elem[j+1])
swap(L.elem[j], L.elem[j+1]);
}
void traverse(sqList L) {
for(int i = 0; i < L.length; i++)
cout<<L.elem[i]<<" ";
cout<<endl;
}
int binary_search(sqList L, int e) {
sort(L);
traverse(L);
int low = 0, high = L.length - 1, mid;
while(low <= high) {
mid = (low + high) / 2;
if(L.elem[mid] == e)
return mid;
else if(L.elem[mid] < e)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
int main() {
sqList L;
init(L);
cout<<binary_search(L, 18);
return 0;
}
折半查找递归算法
#include <stdio.h>
#define MAX 10
typedef int ElemType;
typedef struct {
ElemType *elem;
int length;
} sqList;
void init(sqList &L) {
L.elem = new ElemType[MAX];
L.length = 0;
int e;
for(int i = 0; i < MAX; i++) {
scanf("%d", &e);
L.elem[i] = e;
L.length++;
}
}
void sort(sqList &L) {
int temp;
for(int i = 1; i < L.length; i++)
for(int j = 0; j < L.length - i; j++)
if(L.elem[j] > L.elem[j+1]) {
temp = L.elem[j];
L.elem[j] = L.elem[j+1];
L.elem[j+1] = temp;
}
}
void traverse(sqList L) {
for(int i = 0; i < L.length; i++)
printf("%d ", L.elem[i]);
printf("\n");
}
int binary_search(sqList L, int e, int low, int high) {
int mid;
if(low > high)
return -1;
else {
mid = (low + high) / 2;
if(L.elem[mid] == e)
return mid;
else if(L.elem[mid] < e)
return binary_search(L, e, mid + 1, high);
else if(L.elem[mid] > e)
return binary_search(L, e, low, mid - 1);
}
}
int main() {
sqList L;
init(L);
sort(L);
traverse(L);
int i = binary_search(L, 15, 0, L.length - 1);
printf("%d", i);
return 0;
}