+ Reply to Thread
Results 1 to 2 of 2

Thread: Binary Search , Sequential Search

  1. #1
    Junior Member
    Join Date
    Apr 2012
    Posts
    34

    Binary Search , Sequential Search

    I want example of Binary Search and Sequential Search in javascript.

  2. #2
    Junior Member
    Join Date
    Jan 2012
    Posts
    19
    Binary Search :
    Code:
    searchArray = function(needle, haystack, case_insensitive) {
    	if (typeof(haystack) === 'undefined' || !haystack.length) return -1;
    	
    	var high = haystack.length - 1;
    	var low = 0;
    	case_insensitive = (typeof(case_insensitive) === 'undefined' || case_insensitive) ? true:false;
    	needle = (case_insensitive) ? needle.toLowerCase():needle;
    	
    	while (low <= high) {
    		mid = parseInt((low + high) / 2)
    		element = (case_insensitive) ? haystack[mid].toLowerCase():haystack[mid];
    		if (element > needle) {
    			high = mid - 1;
    		} else if (element < needle) {
    			low = mid + 1;
    		} else {
    			return mid;
    		}
    	}
    	
    	return -1;
    };
    Sequential Search :
    Code:
    <script language="javascript" type="text/javascript">
    var bilar = new Array();
    bilar [0] = 'saab';
    bilar [1] = 'volvo';
    bilar [2] = 'mercedes';
    bilar [3] = 'bmw';
    
    function search(){
    //	var searchForm = document.getElementById("theForm");
    var searchValue = document.getElementById("searchInputForm");
    var resultat = "Bilen finns inte";
    		
    	if (bilar.length<1){
    		document.writeln("arraylistan ?r tom");
    		}
    		
    	else{
    		
    		for (var counter = 0; counter <= bilar.length; ++counter){
    		
    			if (searchValue == bilar[counter]){
    				resultat = "bilen finns!";
    
    				}
    			else{
    				resultat = resultat;
    				}	
    			
    			}//slut p? for
    document.writeln(resultat);
    		
    		}//slut p? else	
    	
    	}//slut p? funktionen
    
    </script>

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts