Skip to content

Instantly share code, notes, and snippets.

@SanjeevMohindra
Last active January 3, 2017 04:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SanjeevMohindra/08f061a37f6843bafeedf628f5a24b49 to your computer and use it in GitHub Desktop.
Save SanjeevMohindra/08f061a37f6843bafeedf628f5a24b49 to your computer and use it in GitHub Desktop.
//Binary Search Algorithm
func binarySearch ( inputSortedData: [Int], searchElement: Int ) -> Int {
var minLeft = 0
var maxRight = inputSortedData.count - 1
while ( minLeft <= maxRight ) {
let middleElement = (minLeft + maxRight) / 2
if (searchElement == inputSortedData[middleElement]) { return middleElement + 1; }
if (searchElement < inputSortedData[middleElement]) { maxRight = middleElement - 1 }
if (searchElement > inputSortedData[middleElement]) { minLeft = middleElement + 1 }
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment