## 基础查找算法（顺序无序查找算法和递归二叉查找算法）

2018-08-06 21:05  蓝之风  阅读(2042)  评论(1编辑  收藏  举报

## 一、顺序无序查找算法

### 1、顺序查找的一般实现：

public static int SqSearch(int[] source, int target)
{
for (int i = 0; i < source.Length; i++)
{
if (source[i] == target)
{
return i;
}
}

return -1;
}

#### 查找最大值

public static int FindMax(int[] source)
{
int max=source[0];
for(int i=1;i<source.Length;i++){
if(max<source[i]){
max=source[i];
}
}
return max;
}

#### 查找最小值

public static int FindMin(int[] source)
{
int min = source[0];
for (int i = 1; i < source.Length; i++)
{
if (source[i] < min)
{
min = source[i];
}
}

return min;
}

### 改变集合数据加快查询效率

public static int Hot20SqSearch(int[] source, int target)
{
for (int i = 0; i < source.Length; i++)
{
if (source[i] == target)
{
if (i > source.Length * 0.2)
{
var temp = source[0];
source[0] = source[i];
source[i] = temp;
}
return i;
}
}

return -1;
}

public static int HotSwapSqSearch(int[] source, int target)
{
for (int i = 0; i < source.Length; i++)
{
if (source[i] == target)
{
if (i > 0)
{
var temp = source[i-1];
source[i-1] = source[i];
source[i] = temp;
}
return i;
}
}

return -1;
}

## 二、二叉查找算法

public static int BinSearch(int[] source, int target)
{
int left = 0, right = source.Length-1,middle;
while (left <= right)
{
middle = (left + right) / 2;
if (source[middle] == target)
{
return middle;
}
else
{
if (source[middle] > target)
{
right = middle - 1;
}
else
{
left = middle + 1;
}
}
}
return -1;
}

## 三、递归实现二叉算法

public static int RBinSearch(int[] source, int target, int left, int right)
{
if (left > right)
{
return -1;
}
else
{
int middle = (int)(left + right) / 2;
if (source[middle] == target)
{
return middle;
}
else
{
if (source[middle] > target)
{
return RBinSearch(source, target, left, right - 1);
}
else
{
return RBinSearch(source, target, left + 1, right);
}
}
}
}