zoukankan      html  css  js  c++  java
  • 分块查找算法

    问题:明白思想,其他的没什么,记得结构体为指针时一定要动态分配内存。

    代码:

    #include <iostream>
    #include <cstdlib>
    
    using namespace std;
    #define MAXL 20
    typedef struct seq
    {
    	int key[MAXL];
    	int len;
    }data;
    
    typedef struct table
    {
    	int start;
    	int end;
    	int d;
    }index[4];
    
    int block_search(index s,data *list,int key)         //分块查找
    {
    	int i=0;
    	int j;
    	while(i<4&&key>s[i].d)     //确定块的地址
    		i++;
    	if(i>=4)
    		return -1;
    
    	for(j=s[i].start;j<=s[i].end;j++)
    	{
    		if(list->key[j]==key)
    			return j;
    	}
    	if(j>s[i].end)
    		return -1;
    
    }
    
    int  main()
    {
    	data *list;
    	index s;
    	int i,j,p;
    	int key;
    	cout<<"/"<<"分块查找"<<"/"<<endl;
    	cout<<"---------------------"<<endl;
    	list=(data *)malloc(sizeof(struct seq));
    	if(!list)
    		cout<<"allocate fail"<<endl;
    
    	cout<<"input the len:";
    	cin>>list->len;
    	for(i=0;i<list->len;i++)
    	{
    		cin>>list->key[i];
    	}
    
    	cout<<"output the list:"<<endl;
    	for(i=0;i<list->len;i++)
    	{
    		cout<<list->key[i]<<"  ";
    	}
    	cout<<endl;
    	for(j=0;j<4;j++)
    	{
    		cin>>s[j].start>>s[j].end>>s[j].d;
    	}
    
    	cout<<"please input the key:";
    	cin>>key;
    	p=block_search(s,list,key);
    	if(p==-1)
    		cout<<"can not find"<<endl;
    	else
    		cout<<"the key pos is  "<<p<<endl;
    	return 0;
    
    }
    

    运行截图:

  • 相关阅读:
    c++ struct 使用
    c++数组、字符串操作
    c++ List、Vector、Stack、Queue使用
    十三、哈希表
    十二、234树
    十一、红黑树
    十、哈夫曼编码
    九、二叉树
    八、高级排序
    七、递归
  • 原文地址:https://www.cnblogs.com/xshang/p/3081358.html
Copyright © 2011-2022 走看看