Last active
December 18, 2016 09:49
-
-
Save zzlalani/d3fbc4810089b583d97d7c8f30b52b19 to your computer and use it in GitHub Desktop.
Binary Search in Typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
import java.lang.*; | |
import java.io.*; | |
class BinSearch { | |
int key; | |
int[] elem; | |
public BinSearch( int key, int[] elem ) { | |
this.key = key; | |
this.elem = elem; | |
} | |
public int search() { | |
int bottom = 0; | |
int top = this.elem.length; | |
int mid; | |
int index = -1; | |
while ( bottom <= top ) { | |
mid = (top + bottom)/2; | |
if ( this.elem[mid] == this.key ) { | |
index = mid; | |
break; | |
} else { | |
if ( this.elem[mid] < this.key ) { | |
bottom = mid + 1; | |
} else { | |
top = mid - 1; | |
} | |
} | |
} | |
return index; | |
} | |
public static void main (String[] args) { | |
int[] elem = {1, 5, 7, 8, 10, 12, 15, 17, 18, 20, 22, 25, 28, 29, 31, 33, 36}; | |
int key = 12; | |
BinSearch bin = new BinSearch(key, elem); | |
int index = bin.search(); | |
System.out.println(String.valueOf(index)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BinSearch { | |
constructor( | |
private key: number, | |
private elem: number[] | |
) { | |
} | |
public search(): number { | |
var bottom: number = 0; | |
var top: number = this.elem.length - 1; | |
var mid: number; | |
var index: number; | |
while ( bottom <= top ) { | |
mid = Math.floor((top + bottom) / 2); | |
if ( this.elem[mid] == this.key ) { | |
index = mid; | |
break; | |
} else { | |
if ( this.elem[mid] < this.key ) { | |
bottom = mid + 1; | |
} else { | |
top = mid - 1; | |
} | |
} | |
} | |
return index; | |
} | |
} | |
let elem = [1, 5, 7, 8, 10, 12, 15, 17, 18, 20, 22, 25, 28, 29, 31, 33, 36]; | |
let key = 12; | |
var bin = new BinSearch(key, elem); | |
let index = bin.search(); | |
alert(index); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment