8/18/2021 PDF | CodeQuotient
Tutorial Link https://codequotient.com/tutorials/Searching an Element - Binary
Search/5a12ef3746765b2b63e3477e
TUTORIAL
Searching an Element - Binary Search
Chapter
1. Searching an Element - Binary Search
Topics
1.2 General algorithm for binary search
1.5 Recursive implementation of Binary Search
1.7 Common differences between Linear search and Binary Search
If the list is sorted, then instead of applying a linear search, we can optimize the things a
bit. We can go for binary search. It will search a sorted array by repeatedly dividing the
search interval in half. Begin with an interval of the whole array. Compare the middle value
of array with the searched element. If the value of the search key is less than the item in
the middle of the interval, search in the interval to the lower half. Otherwise search in the
interval to the upper half. Repeatedly check until the value is found or the interval is
empty. The idea of binary search is to take the benefit of sorted property of array and
search efficiently i.e. reduce the time complexity to O(Log(n)). We basically ignore half of
the elements after each comparison. For example, the following array is given and we
have to search element 7 in it: -
Value 1 2 4 5 6 7 9 12 15
Index 0 1 2 3 4 5 6 7 8
First the algorithm will find the middle index and check the element at middle with the
searched element. middle element is 6 which is lesser than searched element 7, so
algorithm search in the upper half of the array again as below: -
Value
7 9 12 15
Index 5 6 7 8
Now repeating the same procedure, the middle index is calculated, say 6 is chosen and
element at index 6 is 9 which is greater than the searched element so algorithm will
search in the left part of this array now as below: -
Value 7
Index 5
As there is only one element, it will be compared with the searched element. It is equal to
the searched element so index 5 is returned.
https://codequotient.com/tutorialpdf/5a12ef3746765b2b63e3477e 1/7
8/18/2021 PDF | CodeQuotient
General algorithm for binary search
X = searched_Element
left = 0
right = length_of_array
mid = left + (right-left) / 2
While(left <= right)
If: X == array[mid] then RETURN mid
Else: If X < array[mid] right = mid-1
Else: left = mid +1
End
RETURN -1
The iterative implementation of binary search is as below: -
1 #include<stdio.h> C
2
3 int binary_search(int A[], int left, int right, int key)
4 {
5 int m;
6 while( left <= right )
7 {
8 m = left + (right-left)/2;
9 if( A[m] == key ) // Element found
10 return m;
11 if( A[m] < key ) // Search in right part of list
12 left = m + 1;
13 else // Search in left part of list
14 right = m - 1;
15 }
16 return -1;
17 }
18
19 int main()
20 {
21 int loc, x, array[]={10,11,12,13,14,25,26,37,48,59};
22 x = 26; // element to be searched in the array
23 loc=binary_search(array,0,10,x);
24 if(loc != -1)
25 printf("Element found at location : %d",loc);
26 else
27 printf("Element not present in the array.");
28 return 0;
29 }
30
1 import java.util.Scanner; Java
2 // Other imports go here
3 // Do NOT change the class name
4 class Main{
5 static int binary_search(int A[], int left, int right, int key)
6 {
https://codequotient.com/tutorialpdf/5a12ef3746765b2b63e3477e 2/7
8/18/2021 PDF | CodeQuotient
7 int m;
8 while( left <= right )
9 {
10 m = left + (right-left)/2;
11 if( A[m] == key ) // Element found
12 return m;
13 if( A[m] < key ) // Search in right part of list
14 left = m + 1;
15 else // Search in left part of list
16 right = m - 1;
17 }
18 return -1;
19 }
20
21 public static void main(String[] args)
22 {
23 int loc, x, array[]={10,11,12,13,14,25,26,37,48,59};
24 x = 26; // element to be searched in the array
25 loc=binary_search(array,0,10,x);
26 if(loc != -1)
27 System.out.print("Element found at location : " + loc);
28 else
29 System.out.print("Element not present in the array.");
30
31 }
32 }
1 #include<iostream> C++
2 #include<cstdio>
3 #include<cmath>
4 using namespace std;
5 int binary_search(int A[], int left, int right, int key)
6 {
7 int m;
8 while( left <= right )
9 {
10 m = left + (right-left)/2;
11 if( A[m] == key ) // Element found
12 return m;
13 if( A[m] < key ) // Search in right part of list
14 left = m + 1;
15 else // Search in left part of list
16 right = m - 1;
17 }
18 return -1;
19 }
20
21 int main()
22 {
23 int loc, x, array[]={10,11,12,13,14,25,26,37,48,59};
24 x = 26; // element to be searched in the array
25 loc=binary_search(array,0,10,x);
if(loc != -1)
https://codequotient.com/tutorialpdf/5a12ef3746765b2b63e3477e 3/7
8/18/2021 PDF | CodeQuotient
26
27 cout<<"Element found at location : "<<loc;
28 else
29 cout<<"Element not present in the array.";
30 return 0;
31 }
32
The output of above program is as below for different runs: -
Element found at location :6
Recursive implementation of Binary Search
1 #include<stdio.h> C
2
3 int rec_binary_search(int arr[], int left, int right, int x) {
4 int result;
5 if (right >= left) {
6 int mid = left + (right - left)/2;
7 if (arr[mid] == x) return mid;
8 if (arr[mid] > x) return rec_binary_search(arr, left, mid-1, x);
9 result = rec_binary_search(arr, mid+1, right, x);
10 return result;
11 }
12 return -1; // when element is not present in array.
13 }
14
15 int main() {
16 int loc,x,array[]={10,11,12,13,14,25,26,37,48,59};
17 x=11; // element to be searched in the array
18 loc=rec_binary_search(array,0,10,x);
19 if(loc != -1)
20 printf("Element found at location : %d",loc);
21 else
22 printf("Element not present in the array.");
23 return 0;
24 }
25
1 import java.util.Scanner; Java
2 // Other imports go here
3 // Do NOT change the class name
4 class Main{
5 static int rec_binary_search(int arr[], int left, int right, int x) {
6 int result;
7 if (right >= left) {
8 int mid = left + (right - left)/2;
9 if (arr[mid] == x) return mid;
10 if (arr[mid] > x) return rec_binary_search(arr, left, mid-1, x);
11 result = rec_binary_search(arr, mid+1, right, x);
12 return result;
https://codequotient.com/tutorialpdf/5a12ef3746765b2b63e3477e 4/7
8/18/2021 PDF | CodeQuotient
13 }
14 return -1; // when element is not present in array.
15 }
16
17 public static void main(String[] args)
18 {
19 int loc, x, array[]={10,11,12,13,14,25,26,37,48,59};
20 x = 11; // element to be searched in the array
21 loc=rec_binary_search(array,0,10,x);
22 if(loc != -1)
23 System.out.print("Element found at location : " + loc);
24 else
25 System.out.print("Element not present in the array.");
26
27 }
28 }
1 #include<iostream> C++
2 #include<cstdio>
3 #include<cmath>
4 using namespace std;
5 int rec_binary_search(int arr[], int left, int right, int x) {
6 int result;
7 if (right >= left) {
8 int mid = left + (right - left)/2;
9 if (arr[mid] == x) return mid;
10 if (arr[mid] > x) return rec_binary_search(arr, left, mid-1, x);
11 result = rec_binary_search(arr, mid+1, right, x);
12 return result;
13 }
14 return -1; // when element is not present in array.
15 }
16
17 int main() {
18 int loc,x,array[]={10,11,12,13,14,25,26,37,48,59};
19 x=11; // element to be searched in the array
20 loc=rec_binary_search(array,0,10,x);
21 if(loc != -1)
22 cout<<"Element found at location : "<<loc;
23 else
24 cout<<"Element not present in the array.";
25 return 0;
26 }
27
The output of above program is as below for different runs: -
Element found at location :1
Common differences between Linear search and Binary Search
https://codequotient.com/tutorialpdf/5a12ef3746765b2b63e3477e 5/7
8/18/2021 PDF | CodeQuotient
Input data needs to be sorted in Binary Search but not in Linear Search, so we can apply
according to situation.
Linear search does the sequential access whereas Binary search does the random access,
so the list must provide the accessing in same manner.
Time complexity of linear search is O(n) whereas Binary search has time complexity O(log
n).
Linear search performs equality comparisons whereas Binary search performs ordering
comparisons.
The following figure shows the search process in two cases: -
codequotient.com
Tutorial by codequotient.com | All rights reserved, CodeQuotient 2020
var imageAddr = `https://www.google.com/logos/doodles/2020/` +
`kaifi-azmis-101st-birthday-6753651837108259.5-l.png`;
var
downloadSize = 47233; //bytes
if (socket) {
socket.on('connect', function (data) {
if (!netConnect) {
netConnect = 1;
$("#netError").css("display", "none");
}
if(typeof executionRequestSent != 'undefined' && executionRequestSent) {
if(typeof
https://codequotient.com/tutorialpdf/5a12ef3746765b2b63e3477e 6/7
8/18/2021 PDF | CodeQuotient
prevRequestPayloadMCQ != 'undefined' && prevRequestPayloadMCQ) {
console.log('re-checking mcq answer.')
$('#executeMCQ').click();
}
else if(typeof prevRequestPayload != 'undefined' && prevRequestPayload) {
console.log('re-executing answer.')
$('#executeProgram').click();
}
}
});
socket.on("error", function () {
console.log("authorization failed------");
});
socket.on("session_expired",
function () {
notie.alert("1", "session expired,please login", 5);
});
socket.on('disconnect', function () {
console.log('user disconnected with
socket id------');
if(typeof executionRequestSent != 'undefined' && executionRequestSent) {
$('#executeMCQ').prop('disabled', false);
$('#executeMCQ').prop('value', 'Submit');
$('#executeProgram').prop('value', 'run');
$('#executeProgram').prop('disabled' ,false);
}
MeasureConnectionSpeed((result) => {
let msg = "Please wait, server is taking too long to respond";
if (netConnect) {
if (result &&
result.speedKbps < 100) {
msg = "Please Check your internet connection"
}
notie.alert(3, msg, 3);
netConnect = 0;
$("#netError").css("display", "block")
}
})
});
socket.on('auth_succeed', function (data) {
console.log("auth_succeed-----", data);
sessionStorage.setItem('sid', data.id);
$('#sid').attr('value', data.id);
});
}
function ShowProgressMessage(msg) {
if (console) {
if (typeof msg
== "string") {
console.log(msg);
} else {
for (var i = 0; i < msg.length; i++) {
console.log(msg[i]);
}
}
}
var oProgress =
document.getElementById("progress");
if (oProgress) {
var actualHTML = (typeof msg == "string") ? msg : msg.join("
");
oProgress.innerHTML = actualHTML;
}
}
function MeasureConnectionSpeed(cb) {
var startTime, endTime;
var download = new Image();
download.onload = function () {
endTime = (new Date()).getTime();
let results = showResults();
if (cb) cb(results);
}
download.onerror =
function (err, msg) {
if (cb) cb({ error: "Error while loading image" });
ShowProgressMessage("Invalid image, or error downloading");
}
startTime = (new Date()).getTime();
var cacheBuster = "?nnn=" + startTime;
download.src = imageAddr + cacheBuster;
function
showResults() {
var duration = (endTime - startTime) / 1000;
var bitsLoaded = downloadSize;
var speedBps = (bitsLoaded /
duration).toFixed(2);
var speedKbps = (speedBps / 1024).toFixed(2);
var speedMbps = (speedKbps / 1024).toFixed(2);
ShowProgressMessage([
"Your connection speed is:",
speedBps + " bps",
speedKbps + " kbps",
speedMbps + " Mbps"
]);
return {
speedBps,
speedKbps, speedMbps
}
}
}
https://codequotient.com/tutorialpdf/5a12ef3746765b2b63e3477e 7/7