Searching a data set for a value is a ubiquitous computational operation. The simplest method of searching a data set is to start at the beginning and search for the item until either the item is found ot the end of data set is reached. This searching method works best when the data set is relatively small and unordered.
If the data set is ordered, the binary searching algorithm is the better choice. Binary search works by continually subdividing the data set until the item being searched for is found. You can write the binary searching algorithm using both iterative and recursive codes. The Array class in C# includes a built-in binary search method, which should be used whenever a binary search is called for.
ok, let's save the words and goto code!
namespace BasicSearchAlgorithm
{
class CArray
{
//binary seach algorithm
public int binSearch(int[] arr,int value)
{
int upperBound, lowerBound, mid;
upperBound = arr.Length - 1;
lowerBound = 0;
while (lowerBound <= upperBound)
{
mid = (lowerBound + upperBound)/2;
if (arr[mid] == value)
{
return mid;
}
else if (value < arr[mid])
{
upperBound = mid - 1;
}
else
{
lowerBound = mid + 1;
}
}
return -1;
}
}
class Program
{
static void Main(string[] args)
{
int[] arr = new int[10] { 12, 5, 21, 89, 63, 45, 72, 50, 43, 16 };
//Insertion Sort
int inner, temp;
int upper = arr.Length - 1;
for (int i = 1; i <= upper; i++)
{
temp = arr[i];
inner = i;
while (inner > 0 && arr[inner - 1] >= temp)
{
arr[inner] = arr[inner - 1];
inner -= 1;
}
arr[inner] = temp;
}
foreach (int i in arr)
{
Console.Write(i+", ");
}
Console.WriteLine();
//end insertion sort
int seek = 43;
CArray myNum = new CArray();
int position = myNum.binSearch(arr, seek);
if (position > -1)
{
Console.WriteLine(seek+" is found item");
}
else
{
Console.WriteLine("the item "+seek+" is not found");
}
}
}
}
that's a code statement for binary search algorithm. since the sequential search is easier, so we won't write this time.
Thursday, September 25, 2008
Subscribe to:
Post Comments (Atom)


No comments:
Post a Comment