|
-
Oct 29th, 2002, 09:34 AM
#1
Thread Starter
Retired VBF Adm1nistrator
BinarySearch - Is this actually working right ?
Trying to find the average number of iterations to find something using both a sequential linear search, and also a binary search.
Is this working correctly ?
Code:
import java.lang.Math;
public class Linear {
public static void main(String args[]) {
final int DIM = 10000;
int [] searchlist = new int [DIM];
int h, i, j, k, total=0;
for(i = 0; i<DIM; i++)
searchlist[i] = i;
for(i = 0; i<DIM; i++) {
j = (int)(Math.random()*(DIM-1));
k = (int)(Math.random()*(DIM-1));
h = searchlist[j];
searchlist[j] = searchlist[k];
searchlist[k] = h;
}
for(i = 0; i<DIM; i++) {
j = 0;
while(searchlist[j] != i) {
j++;
total++;
}
total++;
}
System.out.println(" Linear : Avg number of comparisons is "+(total/DIM));
total = 0;
for(i = 0; i<DIM; i++) {
total = total + binarySearch(searchlist, i, 0, searchlist.length, 0);
}
System.out.println(" Binary : Avg number of comparisons is "+(total/DIM));
}
public static int binarySearch(int[] c, int x, int left, int right, int iteration) {
if (left == right) {
return iteration;
} else {
int mid = (int)((left + right)/2);
if (x <= c[mid])
return binarySearch(c, x, left, mid, iteration + 1);
else
return binarySearch(c, x, mid+1, right, iteration + 1);
}
}
}
Microsoft MVP : Visual Developer - Visual Basic [2004-2005]
-
Oct 29th, 2002, 04:35 PM
#2
The binarySearch function should work, didn't look at the rest.
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|