zoukankan      html  css  js  c++  java
  • 有序表查找

    #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");
    }
    

      

  • 相关阅读:
    git教程学习笔记(1)
    一句话懂什么是JS闭包
    attachEvent和addEventListener 的使用方法和区别
    地址栏中多个问号如何处理
    事件委托用法
    rem和em的区别
    echarts事件中获取当前实例
    this经典试题
    获取浏览器选中文本并操作
    android Activity launch mode 一个实例 singleInstance
  • 原文地址:https://www.cnblogs.com/wuliqun/p/2418528.html
Copyright © 2011-2022 走看看