View difference between Paste ID: LtPERpaP and 1Gfidrd6
SHOW: | | - or go back to the newest paste.
1
/* Returns either the index of the location in the array,
2
  or -1 if the array did not contain the targetValue */
3
var doSearch = function(array, targetValue) {
4
	var min = 0;
5
	var max = array.length - 1;
6
        var guess;
7
        var iterations = 0;
8
    
9
    while(max>=min){
10
        iterations+=1;
11
        guess = floor((min+max)/2);
12
        
13
        if(array[guess]===targetValue){
14-
            println(iterations)
14+
            println("number of iterations: " + iterations)
15
            return guess;
16
        }
17
        else if(array[guess]<targetValue){
18
            min = guess + 1;
19
        }
20
        else{
21
            max = guess - 1;
22
        }
23
        
24
        println(guess);
25
    }
26
        println(iterations)
27
	return -1;
28
};
29
30
31
32
var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 
33
		41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];
34
35
var result = doSearch(primes, 73);
36
println("Found prime at index " + result);
37
38
Program.assertEqual(doSearch(primes, 73), 20);