Jump to content
IT-პროგრამირების ფორუმი
Sign in to follow this  
Rezo Megrelidze

implementing a generic Binary Search in C#

Recommended Posts

თუ იცით რაარის Binary Search მიხვდებით რას შვება კოდი.

void Main()
{
	// დალაგებული მასივი
	var numb = new[]{1,2,3,6,8,9,14};
	
	Console.WriteLine(BinarySearch(numb,14)); // 6 -- იმიტომ, რომ 14 არის ინდექსით 6-ე.
}

static int BinarySearch<T>(IList<T> list,T key)
{
	return BinarySearch<T>(list,0,list.Count-1,key,new Comparer(CultureInfo.InvariantCulture));
}

static int BinarySearch<T>(IList<T> list,int start, int stop, T key,IComparer comparer)
{
	if(start > stop) return -1;	
	int mid = (start+stop)/2;
	
	if(list[mid].Equals(key)) return mid;
	else if(comparer.Compare(list[mid],key) > 0) 
		return BinarySearch(list,start,mid-1,key,comparer);
	else 
		return BinarySearch(list,mid+1,stop,key,comparer);
}
  • Upvote 2

Share this post


Link to post
Share on other sites
var numb = new[]{1,2,3,6,8,9,14};
bool func(int index, T key)
{
 return comparer.Compare(numb[index], key)>=0;
}

void Main() 
{ 
return BinarySearch<T>(0, 6, key, func, new Comparer(CultureInfo.InvariantCulture)); 
} 

static int BinarySearch<T>(int start, int stop, delegate func, T key, IComparer comparer) 
{
 if(start == stop) 
    return func(mid, key); 
int mid = (start+stop)/2;
 if (func(mid, key))
    return BinarySearch(list,start,mid,key,comparer);
 else 
    return BinarySearch(list,mid+1,stop,key,comparer); 
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

×