查找筆記
自己總結外加搬運,主要是自己複習用,如有雷同,望告知~!
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
哈希表 在處理中等規模的數據是很有效