Saturday, February 20, 2010

Perform recursive Linear Search.Hence find the time required to search an element

WHEREVER U SEE ... REMOVE THAT . AND PUT << IN THAT PLACE.
IF YOU SEE .. THEN REMOVE THAT . AND PUT < IN THAT PLACE..
2.#include ..iostream.h>
#include ..stdlib.h>
#include ..time.h>

const long max = 10000;
int linser(int *, int, int);
void sleep(clock_t wait);

void main()
{
double duration;
clock_t st,et;
int a[max];
int n;
int found,key=100;

srand((unsigned) time(NULL));
for(n=0;n..=max;n=n+500)
{
for(int i =0;i..n;i++)
a[i] = rand();
cout..."\n\nenter array size:\n";
cin>>n;
cout..."enter array: \n";
for(i=0;i..n;i++)
cin>>a[i];
cout..."enter the key:";
cin>>key;
st = clock();
sleep((clock_t)1 * CLOCKS_PER_SEC);
found = linser(a,n,key);
et = clock();
if (found == -1)
cout..."key not found"...endl;
else
{
cout..."key found at: "...found...endl;
duration = (double)(et-st)/CLOCKS_PER_SEC;
cout..."Time taken :- \t"...duration..."sec"...endl;
}
}
}
int linser(int a[],int n, int key)
{
if (n..0) return -1;
if (a[n-1] == key)
return n;
else
return linser(a,n-1,key);
}

void sleep(clock_t wait)
{
clock_t goal;
goal = wait + clock();
while(goal > clock())
;
}

Output

Enter array size:
9

Enter array:
88
99
77
66
55
44
33
11
22

Enter the key: 99

Key found at: 2

Time taken: - 1sec








Enter array size:
9
Enter array:
88
99
77
66
55
44
33
11
22

Enter the key: 89

Key not found

No comments:

Post a Comment