顺序查找 & 折半查找

顺序查找

#include <iostream>
#define MAX 10
using namespace std;
typedef int ElemType;
//建顺序表,下标为0的空间留空 
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;
}
发布了44 篇原创文章 · 获赞 0 · 访问量 866

猜你喜欢

转载自blog.csdn.net/Komatsu_1137/article/details/103787412