write a c program for Probability search using array data structure
#include<stdio.h>
#include<stdlib.h>
int compcount=0;
int probabilityLinearsearch(int A[],int n, int key)
{
int i,temp;
for (i = 0; i < n; i++)
{
compcount ++;
if(A[i]== key )
// Move the element one postion up
if(i!=0) /* check if it is not first postion */
{
temp=A[i];
A[i]=A[i-1];
A[i-1]=temp;
return i; /* return new postion of key */
}
}
return -1; /* key is not found */
}
void accept (int A[],int n){
int i;
printf("Enter the %d element ",n);
for(i=0;i<n;i++)
scanf("%d",&A[i]);
}
void main(){
int A[20],n,key,pos;
printf("How many numbers:-");
scanf("%d",&n);
accept(A,n);
printf("Enter the key to be searched :-");
scanf("%d",& key);
pos=probabilityLinearsearch(A,n,key);
if (pos == -1)
printf("\n %d not foound in the array",key);
else
printf("\n %d found at position %d",key,pos);
printf("\n the total number of comparisons = %d \n ",compcount);
}
0 Comments