#include<iostream>
using namespace std;
typedef struct Node{
int key;
char value;
}Node,*NodePtr;
typedef struct SequentialList{
int length;
NodePtr elements;
}SequentialList,*ListPtr;
ListPtr initList(int* paraKeys, char* paraValues, int paraLength){
int i;
ListPtr resultPtr=(ListPtr)malloc(sizeof(struct SequentialList));
resultPtr->length=paraLength;
resultPtr->elements=(NodePtr)malloc((paraLength+1)*sizeof(struct Node));
for (i = 0; i < paraLength; i ++){
//printf("setting key for index %d: %d and value: %c\r\n", i, paraKeys[i], paraValues[i]);
resultPtr->elements[i+1].key=paraKeys[i];
resultPtr->elements[i+1].value=paraValues[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 0;
}
在这段代码中,我学习了如何实现顺序查找和二分查找两种不同的查找算法。通过学习代码,我了解到了以下几点心得体会:
-
顺序查找:
- 顺序查找从第一个元素开始逐个比较查找关键字,适用于元素数量较少且未排序的情况。
- 在顺序查找测试中,我注意到顺序查找的时间复杂度为O(n),因为它需要逐个遍历查询元素,如果数据量大,效率可能较低。
-
二分查找:
- 二分查找是在已排好序的数组中进行查找,通过不断缩小查找范围来快速定位目标元素。
- 二分查找的时间复杂度为O(log n),效率比顺序查找高很多,适用于大型数据集的查找。