顺序查找

 · 2022-7-23 · 次阅读


根据王道教材编写的顺序查找的代码。顺序查找的思路比较简洁,但是需要注意哨兵的使用方法。

/*
	时间:2022年7月23日20:42:30
	作者:Mythe
	根据王道书上的代码,写的顺序查找的示例。
	在本例中注意理解哨兵的作用。
	哨兵不能让程序运行更快,但是能简化思考的逻辑,减少if语句的使用。
*/
# include <stdio.h>
# include <stdlib.h>
# include <time.h>

typedef struct {
	int * elem;
	int length;
}L, *SeqList;

// 顺序查找
int SeqSearch(SeqList L, int key)
{
	int i = L->length - 1;			// 初始指针指向末尾
	
	L->elem[0] = key;				// 0号位置放哨兵
	while (L->elem[i] != key) {		// 即使待查找的表里面没有指定关键字,也必定会在0号位置找到指定关键字
		i--;						// 从后往前依次找
	}
	return i - 1;					// 返回非-1的数表示查找成功,否则查找失败
}

// 填充数据
void InitList(SeqList L)
{
	srand(time(NULL));
	L->length = 1;
	L->elem = (int *)malloc(sizeof(int) * 11);
	L->elem[0] = 0;								// 第一个位置为无效数据
	int i = 0;
	for (i=0; i<10; i++) {
		L->elem[L->length] = rand() % 100;
		L->length++;
	}
}

// 导出数据
void PrintList(SeqList L)
{
	int i = 0;
	for (i=1; i<L->length; i++) {
		printf("%d ", L->elem[i]);
	}
	printf("\n");
}

int main(void)
{
	int key = 0;
    SeqList L = (SeqList)malloc(sizeof(SeqList));
	InitList(L);
	printf("------ 顺序查找演示程序 ------\n待查找数组:");
	PrintList(L);
	printf("输入要查找的关键字:");
	scanf("%d", &key);
	printf("您查找的关键字所在的数组下标为%d\n若数组下标为-1则查找失败。\n", SeqSearch(L, key));

    
    return 0;
}

运行截图:

image.png

image-20220723204611322