//Make an array with a set of numbers in it
var integerSet = function(num) {
if(!num || num < 1){ num = 10000;}
int_array = [];
for(i=0; i < num; i++){
int_array.push(i);
}
return int_array;
}
var runLinearSearch = function(list, target){
var result;
var value;
console.log(target);
for(var i = 0; i < list.length; i++){
value = list[i];
if(value === target){
result = i;
break;
}
}
return result;
};
var runBinarySearch = function(items, value) {
//Copyright 2009 Nicholas C. Zakas. All rights reserved.
//MIT-Licensed, see source file
var startIndex = 0,
stopIndex = items.length - 1,
middle = Math.floor((stopIndex + startIndex)/2);
while(items[middle] != value && startIndex < stopIndex){
//adjust search area
if (value < items[middle]){
stopIndex = middle - 1;
} else if (value > items[middle]){
startIndex = middle + 1;
}
//recalculate middle
middle = Math.floor((stopIndex + startIndex)/2);
}
//make sure it's the right value
return (items[middle] != value) ? -1 : middle;
}
// Linear search
$('.search').click(function() {
var array_length = $(".number_in").val();
if((array_length / 2) == 0){ array_length = 10000; }
//Get an integer set of array_length numbers
var newIntegerSet = integerSet(array_length);
//Get the value to search
var search_value = $(".number_in").val();
var t0 = performance.now();
var lsResult = runLinearSearch(newIntegerSet, search_value);
var t1 = performance.now();
console.log("Call to runLinearSearch took " + (t1 - t0) + " milliseconds.")
// Binary Search
var t0 = performance.now();
var lsResult = runBinarySearch(newIntegerSet, search_value);
var t1 = performance.now();
console.log("Call to runBinarySearch took " + (t1 - t0) + " milliseconds.")
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.