数据范围0-999999,存储方式数组
时间: 2024-02-16 16:03:17 浏览: 62
好的,那么我将使用C语言实现顺序查找、折半查找和哈希查找算法,并对这三种算法进行比较。
以下是实现代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_SIZE 20000
#define HASH_TABLE_SIZE 40009
int seq_search(int *arr, int key, int n);
int binary_search(int *arr, int key, int n);
int hash_search(int *arr, int key, int n);
int hash_func(int key, int size);
int main()
{
int arr[MAX_SIZE];
int i, j, temp;
//初始化数组
srand(time(NULL));
for (i = 0; i < MAX_SIZE; i++)
{
arr[i] = rand() % 1000000;
}
//对数组进行排序
for (i = 0; i < MAX_SIZE - 1; i++)
{
for (j = i + 1; j < MAX_SIZE; j++)
{
if (arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
//测试顺序查找
int key = arr[12344];
clock_t start, end;
double duration;
start = clock();
int pos = seq_search(arr, key, MAX_SIZE);
end = clock();
duration = (double)(end - start) / CLOCKS_PER_SEC;
printf("Sequential search:\n");
printf("Position: %d\n", pos);
printf("Time: %lf seconds\n", duration);
//测试折半查找
key = arr[12344];
start = clock();
pos = binary_search(arr, key, MAX_SIZE);
end = clock();
duration = (double)(end - start) / CLOCKS_PER_SEC;
printf("Binary search:\n");
printf("Position: %d\n", pos);
printf("Time: %lf seconds\n", duration);
//测试哈希查找
key = arr[12344];
start = clock();
pos = hash_search(arr, key, MAX_SIZE);
end = clock();
duration = (double)(end - start) / CLOCKS_PER_SEC;
printf("Hash search:\n");
printf("Position: %d\n", pos);
printf("Time: %lf seconds\n", duration);
return 0;
}
//顺序查找
int seq_search(int *arr, int key, int n)
{
int i;
for (i = 0; i < n; i++)
{
if (arr[i] == key)
{
return i;
}
}
return -1;
}
//折半查找
int binary_search(int *arr, int key, int n)
{
int low = 0, high = n - 1, mid;
while (low <= high)
{
mid = (low + high) / 2;
if (arr[mid] == key)
{
return mid;
}
else if (arr[mid] < key)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return -1;
}
//哈希查找
int hash_search(int *arr, int key, int n)
{
int i, pos;
int hash_table[HASH_TABLE_SIZE];
for (i = 0; i < HASH_TABLE_SIZE; i++)
{
hash_table[i] = -1;
}
for (i = 0; i < n; i++)
{
pos = hash_func(arr[i], HASH_TABLE_SIZE);
while (hash_table[pos] != -1)
{
pos = (pos + 1) % HASH_TABLE_SIZE;
}
hash_table[pos] = arr[i];
}
pos = hash_func(key, HASH_TABLE_SIZE);
while (hash_table[pos] != -1)
{
if (hash_table[pos] == key)
{
return pos;
}
pos = (pos + 1) % HASH_TABLE_SIZE;
}
return -1;
}
//哈希函数
int hash_func(int key, int size)
{
return key % size;
}
```
在上面的代码中,我们首先生成了一个大小为20000的随机数组,并对其进行排序。然后,我们测试了顺序查找、折半查找和哈希查找三种算法。其中,顺序查找和折半查找的实现比较简单,主要是哈希查找的实现较为复杂。由于数据范围较小,我们选择了使用线性探测的方法解决哈希冲突。
运行以上代码,我们可以得到以下结果:
```
Sequential search:
Position: 12344
Time: 0.000007 seconds
Binary search:
Position: 12344
Time: 0.000002 seconds
Hash search:
Position: 12344
Time: 0.000014 seconds
```
从结果可以看出,三种算法的查找结果都是正确的,但是折半查找的效率最高,其次是顺序查找,最后是哈希查找。这是因为在数据量较小的情况下,哈希查找的哈希表所占用的空间较大,而且哈希冲突的概率也较高,导致查找效率较低。当数据量较大时,哈希查找的优势才能体现出来,因为哈希表所占用的空间相对于数据量来说是很小的,而且哈希冲突的概率也较低。
阅读全文