In day to today programming we face lot of situations where we need to find something in the stored data. Generally the data is organized as arrays or in any form grouped together. If we are adding data to the already existing group we generally tend to add new data at the end of the group.
This leads to unsorted data. Searching unsorted data is time consuming. We have to go one element by element to find the desired data. consider basic scenario where we have 10 numbers stored in an array and that is unsorted. If we want to find if the desired number is present in that array or not then we have to read each element and we have to compare that with the desired one. If we put all the above in form of algorithm:
read the element from array
compare the element with the desired one
if both are matching stop the search we have desired one in array
else continue till we get the desired one or we reach end of array.
int getIndex(int *data, int length, int num)
{
int i;
for ( i = 0; i < length; i++)
{
if ( data[i] == num )
{
return i;
}
}
return length+1;
}
and the main function to use the algorithm is
int main ()
{
int a[10] = {1,2,56,34,21,67,22,99,88,0};
int index = getIndex(a,10,9);
if (index < 10)
{
printf ("The desired element is at position %d",index+1);
}
else
{
printf ("There is no such element in Array");
}
}
in the function getIndex we are returning the index of the element if the desired number is present in array. If the desired number is not present in array we are returning length+1 so that the code in main function knows that there is no number which is matching our requirement.
This leads to unsorted data. Searching unsorted data is time consuming. We have to go one element by element to find the desired data. consider basic scenario where we have 10 numbers stored in an array and that is unsorted. If we want to find if the desired number is present in that array or not then we have to read each element and we have to compare that with the desired one. If we put all the above in form of algorithm:
read the element from array
compare the element with the desired one
if both are matching stop the search we have desired one in array
else continue till we get the desired one or we reach end of array.
int getIndex(int *data, int length, int num)
{
int i;
for ( i = 0; i < length; i++)
{
if ( data[i] == num )
{
return i;
}
}
return length+1;
}
and the main function to use the algorithm is
int main ()
{
int a[10] = {1,2,56,34,21,67,22,99,88,0};
int index = getIndex(a,10,9);
if (index < 10)
{
printf ("The desired element is at position %d",index+1);
}
else
{
printf ("There is no such element in Array");
}
}
in the function getIndex we are returning the index of the element if the desired number is present in array. If the desired number is not present in array we are returning length+1 so that the code in main function knows that there is no number which is matching our requirement.
No comments:
Post a Comment