>On the other hand hashing offers avoiding comparisions
A better explanation would be that binary search repeatedly divides the working range in half until the item is found or the search cannot continue. On the hand, hashing uses a transformation of the data being searched for to create an index in an unordered table.
>Maybe hashing is not for searching at all.
Of course it is. You just neglected to create a hash table.
>Is there any way to implement hashing with my example above or not?
There are many ways to implement hashing with your example. Here is one way:
Code:
#include <iostream>
using namespace std;
const int capacity = 11; // Hash table big enough for all possible elements
int hash_table[capacity]; // Existence hash table 0==not present, 1==present
void bubble_sort(int array[],int length)
{
int swapflag=1;
for(int i=0;i<(length-1) && swapflag;i++)
{
swapflag=0;
for(int j=0;j<(length-(i+1));j++)
if(array[j]>array[j+1])
{
swap(array[j],array[j+1]);
swapflag=1;
}
}
}
int* binary_search(int array[],int value,int length)
{
int head=0,end=length-1,middle;
bubble_sort(array,length);
while(head<=end)
{
middle=(head+end)/2;
if(array[middle]==value)
return &array[middle];
else if(value>array[middle])
head=middle+1;
else
end=middle-1;
}
return 0;
}
int hash_function(int key)
{
return key;
}
void build_hash_table(int array[],int length)
{
for(int i=0;i<length;i++)
hash_table[hash_function(array[i])]=1;
}
int main ( )
{
int array[]={10,8,9,5,6,7,3,2,1,4};
int* x;
bubble_sort(array,10);
x=binary_search(array,5,10);
if(!x)
cout<<"element doesn't exist\n";
else
cout<<"binary search succeeded\n";
build_hash_table(array,10);
int y=hash_table[hash_function(5)];
if(!y)
cout<<"element doesn't exist\n";
else
cout<<"hash table search succeeded\n";
return 0;
}