ProDeveloperTutorial.com

Tutorials and Programming Solutions
Menu
  • Shell Scripting
  • System Design
  • Linux System Programming
  • 4g LTE
  • Coding questions
  • C
  • C++
  • DSA
  • GIT
  • 450 DSA Cracker
  • 5G NR
  • O-RAN

Searching Algorithm 2: Binary Search implementation in C language

prodevelopertutorial April 19, 2019

Binary search is a simple search technique that works on sorted array, either it can be ascending or descending.

Below are the steps to perform binary search:

  1. Binary search can be similar to searching a word in a dictionary. We open the book in the middle and check if the name is found.
  2. If the word is not found, depending upon the results we get we tend to move forward or backward.
  3. If the word is found, then we take the meaning of that word.

Program Design:

Program design is very simple.

  1. We consider first element as low and the last element as high. i.e. the array should be sorted.
  2. We get the index of middle element by using below formula:
    1. mid = (low + high) / 2.
  3. Then we compare the value of middle element with the key as shown below:
    1. If (key == a[mid]) return mid.
  4. Suppose if the key is not found in that index, we check if the key is lower or higher than the mid value. Suppose if the key value is lower, then we change the high to the mid element and repeat step 1.
If(key < a[mid])
	High = mid -1
Else
	Low = mid + 1

Understanding Binary Search with the help of an example:

Basically from the above explanation, there will be 3 cases.

Case 1: When the key  == array[mid]. In this case we exit the loop

Case 2: When key > array[mid]. In this case we move towards right half of the array.

Case3: When key < array[mid]. In this case we move towards left half of the array.

Example:

Consider the sorted array 
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
key = 2

First Pass: 
	[8/2] = 4
	is arr[4] == 2 ? No, and 2 < 5. Hence discard right half and move towards left half.

Second Pass: 
	[3/2] = 2
	is arr[2] == 2 ? No, and 2 < 3. Hence discard right half and move towards left half.

Third Pass: 
	[1/2] = 1
	is arr[1] == 2 ? Yes, hence our result.

C code for binary search:

#include<stdio.h>

void binary_Search(int *array, int len, int key)
{

	int i = 0;

	int min_index = 0;
	int max_index = len-1;

	while(min_index <= max_index) 
	{
		// calculate the mid index
		int mid = (min_index + max_index) / 2;
		printf("mid = %d\n",array[mid] );
		// check if we get the key
		if(array[mid] == key) 
		{
			printf("Key has been found\n");
			return; 
		}

		// traverse in the right side
		else if(array[mid] < key) 
		{
			min_index = mid + 1;
		}
		// traverse in the left side
		else 
		{
			max_index = mid - 1;
		}
	}

	printf("Not able to find key\n");

}

int main()
{
	int arr[5] = {10, 30, 45, 48, 78};

	int arrayLen = 5;

	int key = 45;

	int key_2 = 34;

//successful search
	binary_Search(arr,arrayLen, key);

//key not found case
	binary_Search(arr,arrayLen, key_2);

return 0;
}

 

Run time at worst case for binary search:

In the worst case, we reduce from n to n/2

n/2 to n/4

n/4 to n/8, we reduce till we arrive at 1.

Hence n/ 2^k = 1

K = log n.

Hence at worst case, it will take [log n].

Further Reading:

AJ’s definitive guide for DS and Algorithms. Click here to study the complete list of algorithm and data structure tutorial. 85+ chapters to study from.

 

List Of Tutorials available in this website:

C Programming 20+ ChaptersC++ Programming 80+ Chapters
100+ Solved Coding QuestionsData Structures and Algorithms 85+ Chapters
System design 20+ ChaptersShell Scripting 12 Chapters
4g LTE 60+ ChaptersMost Frequently asked Coding questions
5G NR 50+ ChaptersLinux System Programming 20+ chapters
Share
Email
Tweet
Linkedin
Reddit
Stumble
Pinterest
Prev Article
Next Article

About The Author

prodevelopertutorial

Follow this blog to learn more about C, C++, Linux, Competitive Programming concepts, Data Structures.

One Response

  1. Praveen
    Log in to Reply

    please share some java programming with data structure

    April 29, 2019

Leave a Reply Cancel Reply

You must be logged in to post a comment.

ProDeveloperTutorial.com

Tutorials and Programming Solutions
Copyright © 2023 ProDeveloperTutorial.com
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Do not sell my personal information.
Cookie SettingsAccept
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT