Created
August 17, 2018 19:25
-
-
Save arjunsk/c179a6f3ed8059ade41cb9a7b2ee855e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
package noun; | |
import algorithms.LargerSorter; | |
import algorithms.MediumSorter; | |
import algorithms.SmallSorter; | |
import algorithms.ISorter; | |
public class BinarySearch { | |
ISorter sc; | |
int array[]; | |
public BinarySearch(){} | |
public void setArray(int array[]){ | |
//Instead of this, you could also set type, dynamically. | |
if(array.length <= 100) | |
sc = new SmallSorter(); | |
else if(array.length<=2500) | |
sc = new MediumSorter(); | |
else | |
sc = new LargerSorter(); // parallel sort is efficient if the array size is 2500 | |
/* can also perform, something similar, with compression algorithm, cryptography etc | |
* i.e. compression : based on the file size | |
* cryptography : based on available memory etc. | |
* | |
* Reference :https://stackoverflow.com/questions/370258/real-world-example-of-the-strategy-pattern | |
* This is the core part. | |
*/ | |
this.array = array; | |
sc.sort(this.array); | |
} | |
public int search(int val){ | |
int low, high, mid; | |
low = 0; | |
high = this.array.length; | |
while(low <= high){ | |
mid = (low + high)/2; | |
if(this.array[mid] == val) | |
return mid; // need to handle duplicate value scenario | |
else if( this.array[mid] < val) | |
low = mid+1; | |
else | |
high = mid-1; | |
} | |
return -1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment