#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef int ElemType;
typedef struct {
ElemType* elem;//整型指针
int TableLen;//存储动态数组里边的元素个数
}SSTable;
int Search_Seq(SSTable ST, ElemType key)
{
ST.elem[0] = key;//零号元素作为哨兵
int i;
for (i = ST.TableLen - 1; ST.elem[i] != key; --i)
return i;
}
//init进行了随机数生成
void ST_Init(SSTable& ST, int len)
{
ST.TableLen = len + 1;//多申请了一个位置,为了存哨兵
ST.elem = (ElemType*)malloc(sizeof(ElemType) * ST.TableLen);
int i;
srand(time(NULL));//随机数生成
for (i = 0; i < ST.TableLen; i++)
{
ST.elem[i] = rand ()% 100;
}
}
void ST_print(SSTable ST)
{
for (int i = 0; i < ST.TableLen; i++)
{
printf("%3d", ST.elem[i]);
}
printf("\n");
}
//时间复杂度 logn
int Binary_Search(SSTable L, ElemType key)
{
int low = 0, high = L.TableLen - 1, mid;
while (low <= high)
{
mid = (low + high) / 2;
if (L.elem[mid] == key)
return mid;//等于找到了
else if (L.elem[mid] > key)
high = mid - 1;
else
low = mid + 1;
}
return -1;//没找到
}
int compare(const void* left, const void* right)//left和right代表数组中任意两个值怎么比
{
return *(ElemType*)left - *(ElemType*)right;//返回正值是从小到大,返回负值就是从大到小
}
int main()
{
SSTable ST;
ElemType key;
int pos;//存储查询元素的位置
ST_Init(ST, 10);
ST_print(ST);
printf("请输入要搜索的key值:\n");
scanf("%d", &key);
pos = Search_Seq(ST, key);
if (pos!=10)
{
printf("查找成功 位置为%d\n", pos);
}
else
{
printf("查找失败\n");
}
//二分数组方法
qsort(ST.elem, ST.TableLen, sizeof(int), compare);//qsort实现的是快排,二分前提
ST_print(ST);
printf("二分查找,请输入要搜索的key值:\n");
scanf("%d", &key);
//有序数组
pos = Binary_Search(ST, key);//二分查找,折半查找
if (pos!=-1)
{
printf("查找成功 位置为%d\n", pos);
}
else
{
printf("查找失败\n");
}
return 0;
}
7.4 散列表
#define MaxKey 1000
#include<stdio.h>
int hash(const char* key)
{
int h = 0, g;
while (*key)
{
h = (h << 4) + *key++;
g = h & 0xf0000000;
if (g)
{
h ^= g >> 24;
}
h &= ~g;
}
return h % MaxKey;//算出下标要取余
}
int main()
{
const char* pStr[5] = { "xiongda","lele","hanmeimei","dasfg","dsag" };
int i;
const char* pHash_table[MaxKey] = { NULL };
for (i = 0; i < 5; i++)
{
printf("%s is key=%d\n", pStr[i], hash(pStr[i]));
pHash_table[hash(pStr[i])] = pStr[i];
}
}