import javax.swing.*;
public class LinearSearch{
int [] array;
int n;
public LinearSearch(int n){
this.n = n;
array = new int[n];
for(int i = 0; i< n; i++){
array[i]=getRandom(0,2*n);
}
}
public int search(int key){
int index=0;
while (index < n && key!=array[index]) index++;
if (index==n) return -1;
return index;
}
public static int getRandom(int from, int to){
return (int)Math.round(Math.random()*(to-from)+from);
}
public void shortarray(int arraySize){
int temp=0;
for(int i=0;i<arraySize;i++){
for(int j=i;j<arraySize;j++){
if(array[i]>array[j]){
temp=array[i];
array[i]=array[j];
array[j]=temp;
}
}
}
/*System.out.println();
for(int i=0;i<2000;i++){
System.out.print(array[i]+" ");
}*/
}
public static void main(String args[]){
int arraySize=2000;
LinearSearch ls = new LinearSearch(arraySize);
ls.shortarray(arraySize);
for(int repeat=0; repeat< 100; repeat++){
int numberOfTries=5000;
int key, result;
int successCount=0;
int failureCount=0;
int averageComparisonForSuccess=0;
for(int i=0; i< numberOfTries; i++){
key=ls.getRandom(0,2*arraySize);
result=ls.search(key);
if (result==-1) failureCount++;
else{successCount++;
averageComparisonForSuccess+=result+1;
}
}
if (successCount>0) averageComparisonForSuccess=averageComparisonForSuccess/successCount;
String analysisResult="---Search Analysis Report "+(repeat+1)+"---\n"+
"Array Size="+ls.array.length+
"\nNumber of Tries="+numberOfTries+
"\nSuccessfull Searches="+successCount+"\n"+
"Unsuccessfull Searches="+failureCount+"\n"+
"Average Count of Comparisons in Successfull Searches="+ averageComparisonForSuccess+
"\n---End of Report--\n";
System.out.println(analysisResult);
}
}
}
No comments:
Post a Comment