文章目录
- 一、顺序查找
- 二、折半查找
一、顺序查找
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef struct {//查找表的数据结构int *data;//动态数组基址int TableLen;//表长
}SSTable;void InitTable(SSTable *L) {//初始化一个动态分配的顺序表:5,3,2,4,7,6,1,9,8,0L->data = (int*)malloc(sizeof(int) * 10);L->TableLen = 10;int arr[10] = { 5,3,2,4,7,6,1,9,8,0 };for (int i = 0;i < L->TableLen;i++) {L->data[i] = arr[i];}
}//顺序查找
int Search_Seq(SSTable ST,int key)//在ST表中查找key,返回key下标,没找到返回-1
{int i = 0;for (i = 0;i < ST.TableLen;i++) {if (ST.data[i] == key) {return i;}}//上面还没return出去说明没找到return -1;
}int main()
{SSTable ST;InitTable(&ST);int key = 0;printf("请输入要查的元素,将返回给你元素下标:");scanf("%d", &key);int x = Search_Seq(ST,key);if (x != -1) {printf("要查元素的下标为:%d", x);}else {printf("表中无该元素");}return 0;
}
二、折半查找
#include<stdio.h>
#include<stdlib.h>
typedef struct {//查找表的数据结构int *data;//动态数组基址int TableLen;//表长
}SSTable;void InitTable(SSTable *L) {//初始化一个动态分配的顺序表:5,3,2,4,7,6,1,9,8,0L->data = (int*)malloc(sizeof(int) * 10);L->TableLen = 10;int arr[10] = { 1,4,7,8,56,89,90,95,100,121 };for (int i = 0;i < L->TableLen;i++) {L->data[i] = arr[i];}
}//折半查找
//ps:折半查找的数组必须是有序的
//假设我们这里的测试数组是升序:1,4,7,8,56,89,90,95,100,121
int Binary_Search(SSTable ST,int key) {int low = 0;int high = ST.TableLen - 1;int mid = 0;while (low <= high) {mid = (low + high) / 2;if (ST.data[mid] == key) {return mid;}else if (ST.data[mid] > key) {high = mid - 1;}else {low = mid + 1;}}//到这里还没return出去,说明没找到return -1;
}int main()
{SSTable ST;InitTable(&ST);int key = 0;printf("请输入要查的元素,将返回给你元素下标:");scanf("%d", &key);int x = Binary_Search(ST, key);if (x != -1) {printf("要查元素的下标为:%d", x);}else {printf("表中无该元素");}return 0;
}