顺序查找与二分查找

#include <stdio.h>
#include <malloc.h>

typedef struct Node {
	int key;
	char value;
}Node,*NodePtr;

typedef struct SequentialList {
	int length;
	NodePtr elements;
}SequentailList,*ListPtr;


ListPtr initList(int* paraKeys, char* paraValue, int paraLength) {
	int i;
	ListPtr resultPtr = (ListPtr)malloc(sizeof(struct SequentialList));
	resultPtr->length = paraLength;
	resultPtr->elements = (NodePtr)malloc(sizeof(struct Node) * (paraLength + 1));

	for (i = 0; i < paraLength; i++) {
		resultPtr->elements[i+1].key = paraKeys[i];
		resultPtr->elements[i + 1].value = paraValue[i];

	}

	return resultPtr;
}

char sequentialSearch(ListPtr paraListPtr,int paraKey) {
	int i = paraListPtr->length;
	paraListPtr->elements[0].key = paraKey;
	paraListPtr->elements[0].value = 'x';
	while (paraListPtr->elements[i].key != paraKey) {
		i--;
	}
	return paraListPtr->elements[i].value;
}


void sequentialSearchTest() {
	int tempUnsortedKeys[] = { 4, 5, 3, 6, 10, 7, 1, 9 };
	char tempContents[] = { 'h', 'e', 'l', 'o', 'w', 'r', 'd', '!' };
	ListPtr tempListPtr = initList(tempUnsortedKeys, tempContents, 8);

	printf("Search result of 10 is: %c\r\n", sequentialSearch(tempListPtr, 10));
	printf("Search result of 5 is: %c\r\n", sequentialSearch(tempListPtr, 5));
	printf("Search result of 4 is: %c\r\n", sequentialSearch(tempListPtr, 4));
	printf("Search result of 2 is: %c\r\n", sequentialSearch(tempListPtr, 2));
}

char binarySearch(ListPtr paraListPtr, int paraKey) {
	int tempLeft = 1;
	int tempright = paraListPtr->length;
	int tempMiddle = (tempLeft + tempright) / 2;

	while (tempLeft <= tempright) {
		tempMiddle = (tempLeft + tempright) / 2;
		if (paraListPtr->elements[tempMiddle].key == paraKey) {
			return paraListPtr->elements[tempMiddle].value;
		}
		else if (paraListPtr->elements[tempMiddle].key <= paraKey) {
			tempLeft = tempMiddle + 1;
		}
		else {
			tempright = tempMiddle - 1;
		}
	}
	return 'x';
}

void binarySearchTest() {
	int tempUnsortedKeys[] = { 1, 3, 4, 5, 6, 7, 9, 10 };
	char tempContents[] = { 'h', 'e', 'l', 'o', 'w', 'r', 'd', '!' };
	ListPtr tempListPtr = initList(tempUnsortedKeys, tempContents, 8);

	printf("Search result of 10 is: %c\r\n", binarySearch(tempListPtr, 10));
	printf("Search result of 5 is: %c\r\n", binarySearch(tempListPtr, 5));
	printf("Search result of 4 is: %c\r\n", binarySearch(tempListPtr, 4));
	printf("Search result of 2 is: %c\r\n", binarySearch(tempListPtr, 2));
}

int main() {
	printf("\r\n-------sequentialSearchTest-------\r\n");
	sequentialSearchTest();

	printf("\r\n-------binarySearchTest-------\r\n");
	binarySearchTest();
	return 1;
}

运行结果:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值