• 有序表查找


    #include<stdio.h>
    #include<stdlib.h>
    
    #define EQ(a,b) ((a) == (b))
    #define LT(a,b) ((a) < (b))
    #define LE(a,b) ((a) <= (b))
    
    typedef struct{
    	int key;
    	int data;
    }SElemType;
    
    typedef struct{
    	SElemType *elem;
    	int length;
    }SSTable;
    
    SSTable * create(int n)
    {
    	SSTable *sst = (SSTable *)malloc(sizeof(SSTable));
    	int x;
    	sst->elem = (SElemType*)malloc(sizeof(SElemType) * n);
    	sst->length = n;
    	for(int i = 1; i <= n ; i++)
    	{
    		scanf("%d",&x);
    		sst->elem[i].data = x;
    		sst->elem[i].key = i;
    	}
    	sst->elem[0].key = 0;
    	sst->elem[0].key = 0;
    	return sst;
    }
    
    int search(SSTable * st,int key)
    {
    	int i;
    	st->elem[0].key = key;
    	for( i = st->length ;!EQ(st->elem[i].key,key);--i);
    	return i;
    }
    
    int searchBin(SSTable * st,int key)
    {
    	int low =1,high = st->length ;
    	int mid=0;
    	while(low <= high)
    	{
    		mid = (low + high)/2;
    		if(EQ(key,st->elem[mid].key)) 
    			return mid;
    		else if(LT(key,st->elem[mid].key))
    			high = mid -1;
    		else low = mid +1;
    	}
    	return 0;
    }
    
    void main()
    {
    	printf("Input number of element:\n");
    	int n;
    	scanf("%d",&n);
    	SSTable * sst = create(n);
    	printf("the search table element are:\n");
    	for(int i = 1;i<=n;i++)
    	{
    		printf("%-5d",sst->elem[i].data);
    	}
    	printf("\nposition of key i is:\n");
    	printf("%d\n",search(sst,3));
    
    	printf("\nposition of key i (binary search) is:\n");
    	printf("%d\n",searchBin(sst,3));
    	system("pause");
    }
    

      

  • 相关阅读:
    Java Web学习笔记---用GET实现搜索引擎
    Docker之docker log详解
    Docker之save、load、export、import命令
    Docker之镜像地址
    GIT使用详解
    Docker之commit制作镜像
    Python之sys.arg[]的用法解释
    python常用内置函数
    VBA精彩代码分享-1
    C#读写EXCEL单元格的问题
  • 原文地址:https://www.cnblogs.com/wuliqun/p/2418528.html
Copyright © 2020-2023  润新知