一、线性表查找
1.顺序表查找和链表的普通查找因为比较简单,暂时没有写,以后复习补上。
2.折半查找:
折半查找也称为二分查找,适用于顺序存储结构并且数据元素按照关键字大小排序的线性表。
思路:对于给定值k,从有序表的中间位置开始比较,如果当前数据元素的关键字等于k,则查找成功;否则,若k小于当前数据元素的关键字,则在有序表的前半部分继续查找;反之,则在有序表的后半部分继续查找,直到完成。
步骤:1)设查找给定值k,给left和right初始值,确定有序表长度为n,则mid=(left+right)/2,比较k与table[mid]
2)若k>table[mid],则在有序表的后半部分查找,若k<table[mid],则在有序表的前半部分查找。
3)再比较与table[mid],重复第二步,直至成功。
描述:
算法:
Code
using System;
public class BinarySearch
{
private int[] mat;
private int mid;
private bool find;
public BinarySearch(int[] table)
{
mat=new int[table.Length];
table.CopyTo(mat,0); //数组拷贝
}
public int binarySearch(int k) //查找k值,找到时返回下标,不成功时返回-1
{
int left=0,right=mat.Length-1;
find=false;
while(left<=right && !find) //子序列边界有效
{
mid=(left+right)/2; //子序中间位置
if(mat[mid]==k)
find=true; //查找成功
else
{
if(mat[mid]>k) //子序为原序列的前半部分
right=mid-1;
else //子序为原序列的后半部分
left=mid+1;
}
}
if(find)
return mid;
else
return -1;
}
public int recBinarySearch(int left,int right,int k) //递归实现
{
int ret=-1;
if(left>right) return -1;
mid=(left+right)/2;
if(mat[mid]==k) return mid;
if(mat[mid]<k) ret=recBinarySearch(mid+1,right,k);
if(mat[mid]>k) ret=recBinarySearch(left,mid-1,k);
return ret;
}
public bool Find{get;set;}
public void output()
{
for(int i=0;i<mat.Length;i++)
Console.Write(mat[i]+" ");
Console.WriteLine();
}
public static void Main()
{
Random rom = new Random();
int[] table = {4,7,8,9,15,27,32};
BinarySearch bs=new BinarySearch(table);
Console.WriteLine(bs.binarySearch(27));
Console.WriteLine(bs.recBinarySearch(0,table.Length,27));
}
}
顺便介绍一个折半插入排序:
Code
using System;
public class BinInsertSort
{
private int[] mat;
private int index;
public BinInsertSort(int[] table)
{
mat=new int[table.Length];
table.CopyTo(mat,0); //数组拷贝
}
public void binInsertSort()
{
int[] tmp=new int[mat.Length];
int left,right,mid=0;
// tmp[0]=mat[0];
for(int i=0;i<mat.Length;i++)
{
left=0;
right=i;
while(left<=right)
{
mid=(left+right)/2;
if(mat[i]>=tmp[mid])
right=mid-1;
else
left=mid+1;
}
for(int j=i-1;j>=mid;j--)
tmp[j+1]=tmp[j];
tmp[left]=mat[i];
}
tmp.CopyTo(mat,0);
}
public void output()
{
for(int i=0;i<mat.Length;i++)
Console.Write(mat[i]+" ");
Console.WriteLine();
}
public static void Main()
{
Random rom = new Random();
int[] table = new int[10];
for(int i=0;i<table.Length;i++)
table[i]=rom.Next(1,99); //生成随数放入数组。
BinInsertSort bis=new BinInsertSort(table);
bis.output();
bis.binInsertSort();
bis.output();
}
}
实在不想写到排序里面了,以后再介绍折半插入排序的思路和步骤。