使用哈希存储将数据存入哈希表中,并进行查找

主函数 main.c
#include<stdio.h>
#include<stdlib.h>
#include"hash.h"
int main(int argc, const char *argv[])
{
Node *hash[P];
init_hash(hash);
int a[10]={25,51,8,22,26,67,11,16,54,41};
for (int i=0;i<10;i++)
{
insert_hash(hash,a[i]);
}
show_hash(hash);
search(hash,25);
search(hash,100);
return 0;
}
功能函数.C文件 hash.c
#include<stdio.h>
#include<stdlib.h>
#include"hash.h"
void init_hash(Node **hash)
{
for(int i=0;i<P;i++)
{
hash[i]=NULL;
}
printf("初始化成功\n");
}
void insert_hash(Node **hash,int key)
{
int index=key%P;
Node *p=(Node *)malloc(sizeof(Node));
if(p==NULL)
{
printf("申请空间失败\n");
return ;
}
p->data=key;
p->next=NULL;
p->next=hash[index];
hash[index]=p;
}
void show_hash(Node **hash)
{
for(int i=0;i<P;i++)
{
printf("%d-->",i);
Node *q=hash[i];
while(q!=NULL)
{
printf("%d->",q->data);
q=q->next;
}
printf("NULL\n");
}
}
int search(Node **hash,int x)
{
int i=0;
int index=x%P;
Node *q=hash[index];
while(q!=NULL)
{
i++;
if(q->data==x)
{
printf("找到该数字,是hash表下标为%d的第%d个数字\n",index,i);
return 0;
}
q=q->next;
}
if(q==NULL )
{
printf("你查找的数字不存在\n");
return -1;
}
}
声明.h文件 hash.h
#ifndef __HASH_H__
#define __HASH_H__
#define P 13
typedef int datatype;
typedef struct Node
{
datatype data;
struct Node *next;
}Node;
void init_hash(Node **hash);
void insert_hash(Node **hash,int key);
void show_hash(Node **hash);
int search(Node **hash,int x);
#endif
使用冒泡排序、选择排序、插入排序、快速排序完成下面案例

冒泡排序降序 时间复杂度O(n^2)
#include<stdio.h>
void pop_sort(int a[],int n)
{
int i,j;
for(i=1;i<n;i++)
{
int flag=0;
for(j=0;j<n-i;j++)
{
if(a[j]<a[j+1])
{
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
flag=1;
}
}
if(flag==0)
{
break;
}
}
}
选择排序升序 时间复杂度 O(n^2)
void select_sort(int a[],int n)
{
int i,j;
int index;
int t;
for(i=0;i<n;i++)
{
index=i;
for(j=i;j<n;j++)
{
if(a[index]>a[j])
{
index=j;
}
}
if(i!=index)
{
t=a[i];
a[i]=a[index];
a[index]=t;
}
}
}
插入排序降序 时间复杂度 O(n)到O(n^2)
void search_sort(int a[],int n)
{
int i,j;
int temp;
for(i=1;i<n;i++)
{
temp=a[i];
for(j=i;j>0 && a[j-1]<temp;j--)
{
a[j]=a[j-1];
}
a[j]=temp;
}
}
快速排序函数升序 时间复杂度 O(n*log2n)
int port(int a[],int low,int high)
{
int x=a[low];
while(low<high)
{
while(a[high]>=x &&low<high)
{
high--;
}
a[low]=a[high];
while(a[low]<=x &&low<high)
{
low++;
}
a[high]=a[low];
}
a[high]=x;
return high;
}
void quik_sort(int a[],int low,int high)
{
if(low<high)
{
int mid=port(a,low,high);
quik_sort(a,low,mid-1);
quik_sort(a,mid+1,high);
}
}
主函数
int main(int argc, const char *argv[])
{
int a[5]={5,7,10,3,1};
pop_sort(a,5);
select_sort(a,5);
search_sort(a,5);
quik_sort(a,0,4);
for(int i=0;i<5;i++)
{
printf("\t%d",a[i]);
}
printf("\n");
return 0;
}