interface node {
index: number;
value: any;
}
class Search {
public data: Array<any> = new Array();
constructor() { };
}
//notBinary Search needs shorted data while LinearSearch works on unshorted datae:
class BinarySearch extends Search {
private startIndex: number;
private endIndex: number;
constructor(_data: Array<any>) {
super();
this.data = _data;
}
public search(_value) {
this.startIndex = 0;
this.endIndex = (this.data.length - 1)
while (this.startIndex <= this.endIndex) {
let mid = Math.round(this.startIndex + (this.endIndex - this.startIndex) / 2)
if (this.data[mid] === _value) {
return { index: mid, value: this.data[mid] };
}
(this.data[mid] < _value) ? this.startIndex = (mid + 1) : this.endIndex = (mid - 1);
}
return { index: -1, value: "no value" };;
}
}
var binarySearch = new BinarySearch([1, 2, 3, 4, 5, 6, 17, 18]);
console.log(binarySearch.search(18).index)
Comments
Post a Comment