查找笔记

查找笔记
自己总结外加搬运,主要是自己复习用,如有雷同,望告知~!

1


普通数据查找,对于简单的查找,假设所有数据不重复,所要查找的数据位置不确定,所以要将数据进行遍历才能找到对应的数据。

int find(int array[], int  length, int value)  
{  
    if(NULL == array || 0 == length)  
        return -1;  

    for(int index = 0; index < length; index++){  
        if(value == array[index])  
            return index;  
        }  
    return 

最段时间为O(1),最大为O(n),平均为(1+n)/2。

2

日常中,数据都是有序的,对一个有序的数组,二分查找是最好的方法。
这里就要在查找钱先调用排序算法。

int binary_sort(int array[], int length, int value)  
{  
    if(NULL == array || 0 == length)  
        return -1;  

    int start = 0;  
    int end = length -1;  

    while(start <= end){  

        int middle = start + ((end - start) >> 1);  
        if(value == array[middle])  
            return middle;  
        else if(value > array[middle]){  
            start = middle + 1;  
        }else{  
            end = middle -1;  
        }  
    }  

    return -1

3排序二叉树

对于指针类型的数据,定义排序二叉树,每一个节点记录一个数据同时左分支的数据<根节点<右分支的数据。
链表实现:

#include <stdio.h>
#include <iostream>

using namespace std;

 struct node
{
    int data;
    struct node * lchild;
    struct node * rchild;
};

void Init(node *t)
{
    t = NULL;
}

node * Insert(node *t, int key)
{
    if (t == NULL)
    {
        node * p;
        p = (node *)new(node);
        p->data = key;
        p->lchild = NULL;
        p->rchild = NULL;
        t = p;
    }
    else
    {
        if (key < t->data)
            t->lchild = Insert(t->lchild, key);
        else
            t->rchild = Insert(t->rchild, key);
    }
    return t;    //important!
}

node * creat(node *t)
{
    int i, n, key;
    cout << "要输入多少个数据:";
    cin >> n;
    cout << "输入数据:";
    for (i = 0; i < n; i++)
    {
        cin >> key;
        t = Insert(t, key);
    }
    return t;
}

void InOrder(node * t)        //中序遍历输3出
{
    if (t != NULL)
    {
        InOrder(t->lchild);
        cout << t->data << " ";
        InOrder(t->rchild);
    }
}

int main()
{
    node * t = NULL;
    t = creat(t);
    InOrder(t);
    return 0;
}

4

哈希表 在处理中等规模的数据是很有效

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章