查找
1.线性表查找涉及算法:顺序查找、二分查找、分块查找
//顺序查找,n为数组a的长度
int SequenceSearch(int a[], int value, int n)
{
int i;
for(i=0; i<n; i++)
if(a[i]==value)
return i;
return -1;
}
//二分查找(折半查找),一般方法,n为数组a的长度
int BinarySearch1(int a[], int value, int n)
{
int low, high, mid;
low = 0;
high = n-1;
while(low<=high)
{
mid = (low+high)/2;
if(a[mid]==value) //取中间量
return mid;
else if(a[mid]>value)
high = mid-1; //从前半部分查找
else
low = mid+1; //从后半部分查找
}
return -1;
}
//二分查找,递归方法
int BinarySearch2(int a[], int value, int low, int high)
{
if(low>high)
return -1;
int mid = (low+high)/2;
if(a[mid]==value)
return mid;
else if(a[mid]>value)
return BinarySearch2(a, value, low, mid-1);
else
return BinarySearch2(a, value, mid+1, high);
}
2.树表的查找:二叉排序树和平衡二叉树
3.散列/哈希表查找:
//采用除数取留法确定地址,利用线性开放地址法处理冲突问题,2016.5.28
#include <stdio.h>
#include <stdlib.h>
#include <io.h>
#include <math.h>
#include<time.h>
#define HASHSIZE 15
#define NULLKEY -32768
typedef struct
{
int *elem; //数据元素存储地址
int count;//当前元素个数
}HashTable;
int L = 0; //表的长度
bool init(HashTable *hashTable)//哈希表的初始化
{
int i;
L = HASHSIZE;
hashTable->elem = (int*)malloc(L*sizeof(int));//申请内存
hashTable->count = L;
for (i = 0; i < L; i++)
{
hashTable->elem[i]=NULLKEY;
}
return true;
}
//哈希函数,除留余数法,最常用的哈希函数,还有其它的。
int Hash(int data)
{
return data%L;
}
void insert( HashTable *hashTable, int data)
{
int Addr = Hash(data);//求哈希地址
while (hashTable->elem[Addr] != NULLKEY)//求得地址不是初始化时的空,则表示有元素已经插入,会有冲突
{
Addr = (Addr + 1) % L;//开放地址线性探测,还可以二次探测
}
hashTable->elem[Addr] = data;
}
int find(HashTable *hashTable, int data)
{
int Addr = Hash(data); //求哈希地址
while (hashTable->elem[Addr] != data) //线性开放定址法解决冲突
{
Addr = (Addr + 1) % L;
if (hashTable->elem[Addr] == NULLKEY || Addr == Hash(data))
return 0;
}
return Addr;
}
void display(HashTable *hashTable) //散列元素显示
{
int i;
printf(".........结果展示.........\n");
for (i = 0; i < hashTable->count; i++)
{
printf("%d\n", hashTable->elem[i]);
}
}
void main()
{
int i, j, result, x;
HashTable hashTable;
int arr[HASHSIZE];
printf("请输入少于15个,初始化哈希表的元素:\n");
for (j = 0; j < HASHSIZE; j++)
{
scanf("%d", &arr[j]);
}
init(&hashTable);
for (i = 0; i < HASHSIZE; i++)
{
insert(&hashTable, arr[i]);
}
display(&hashTable);
printf("请输入你要查找的元素:\n");
scanf("%d", &x);
result = find(&hashTable, x);
if (result)
printf("查找元素%d在哈希表中的位置为%d\n",x,result);
else
printf("没找到!\n");
system("pause");
}
参考:c实现查找算法
https://blog.csdn.net/bluesliuf/article/details/89005232
1589

被折叠的 条评论
为什么被折叠?



