How to implement a Binary Search Algorithm in Java without recursion

<br>

An Iterative implementation of the popular binary search algorithm to find an element in a sorted array.


Hello everyone! I have published a lot of algorithms and data structure articles on my blog, but this one is the first one here. In this article, we’ll examine popular fundamental algorithms for interviews.

Yes, you guessed it right: you need to implement a binary search in Java, and you need to write both iterative and recursive binary search algorithms.

In computer science, a binary search, or half-interval search, is a divide and conquer algorithm that locates the position of an item in a sorted array. Binary searching works by comparing an input value to the middle element of the array.

The comparison determines whether the element equals the input, is less than the input, or is greater than the input.

When the element being compared equals the input, the search stops and typically returns the position of the element.

If the element is not equal to the input, then a comparison is made to determine whether the input is less than or greater than the element.

Depending on the result, the algorithm then starts over again, but only searching the top or a bottom subset of the array’s elements.

If the input is not located within the array, the algorithm will usually output a unique value indicating this like -1 or just throw a RuntimeException in Java like NoValueFoundException.

Binary search algorithms typically halve the number of items to check with each successive iteration, thus locating the given item (or determining its absence) in logarithmic time.

Btw, if you are not familiar with fundamental search and sort algorithms, then you can also join a course like Data Structures and Algorithms: Deep Dive Using Java to learn fundamental algorithms.

If Java is not your choice of language, you can find more recommendations for JavaScript and Python in this list of algorithms courses.

Btw, if you prefer books, I suggest you read a comprehensive algorithm book like Introduction to Algorithms by Thomas H. Cormen.

Here is some sample code which shows the logic of iterative binary search in Java:


Binary Search Implementation in Java

Here is a sample program to implement binary search in Java. The algorithm is implemented recursively. Also, an interesting fact to know about binary search implementation in Java is that Joshua Bloch, author of the famous Effective Java book, wrote the binary search in “java.util.Arrays”.


import java.util.Arrays;
import java.util.Scanner;
/**
 * Java program to implement Binary Search. We have implemented Iterative
* version of Binary Search Algorithm in Java
*
* @author Javin Paul
*/
public class IterativeBinarySearch {
  public static void main(String args[]) {
    int[] list = new int[]{23, 43, 31, 12};
    int number = 12;
    Arrays.sort(list);
    System.out.printf("Binary Search %d in integer array %s %n", number, Arrays.toString(list));
    binarySearch(list, 12);
    System.out.printf("Binary Search %d in integer array %s %n", 43, Arrays.toString(list));
    binarySearch(list, 43);
    list = new int[]{123, 243, 331, 1298};
    number = 331;
    Arrays.sort(list);
    System.out.printf("Binary Search %d in integer array %s %n", number,
    Arrays.toString(list));
    binarySearch(list, 331);
    System.out.printf("Binary Search %d in integer array %s %n",   331, Arrays.toString(list));
    binarySearch(list, 1333);
   // Using Core Java API and Collection framework
   // Precondition to the Arrays.binarySearch
   Arrays.sort(list);
   // Search an element
   int index = Arrays.binarySearch(list, 3);
}
/**
 * Perform a binary Search in Sorted Array in Java
 * @param input
 * @param number
 * @return location of element in array
 */
public static void binarySearch(int[] input, int number) {
int first = 0;
int last = input.length - 1;
int middle = (first + last) / 2;
while (first <= last) {
  if (input[middle] &lt; number) {
  first = middle + 1;
} else if (input[middle] == number) {
System.out.printf(number + " found at location %d %n", middle);
break;
} else {
  last = middle - 1;
}
middle = (first + last) / 2;
}
if (first > last) {
  System.out.println(number + " is not present in the list.\n");
}
}
}
Output
Binary Search 12 in integer array [12, 23, 31, 43]
12 found at location 0
Binary Search 43 in integer array [12, 23, 31, 43]
43 found at location 3
Binary Search 331 in integer array [123, 243, 331, 1298]
331 found at location 2
Binary Search 331 in integer array [123, 243, 331, 1298]
1333 is not present in the list.

That’s all about how to implement binary search using recursion in Java. Along with Linear search, these are two of the essential search algorithms you learn in your computer science class.

The binary search tree data structure takes advantage of this algorithm and arranges data in a hierarchical structure so that you can search any node in O(logN) time.

Though, you must remember that in order to use binary search, you need a sorted list or array, so you also need to consider the cost of sorting when you consider using binary search algorithm in the real world.

 

 Further Learning

 Data Structures and Algorithms: Deep Dive Using Java

 Algorithms and Data Structures — Part 1 and 2 

 Data Structures in Java 9 by Heinz Kabutz

10 Algorithms books for Interviews

10 Data Structure and Algorithm Courses for Interviews

5 Free Courses to Learn Data Structure and Algorithms

Other Data Structure and Algorithms tutorials you may like

  • How to implement Quicksort algorithm in place in Java? (tutorial)
  • How to implement Binary Search Tree in Java? (solution)
  • How to implement Quicksort algorithm without recursion? (tutorial)
  • How to implement Insertion sort algorithm in Java? (tutorial)
  • How to implement Bubble sort algorithm in Java? (tutorial)
  • What is the difference between Comparison and Non-Comparison based sorting algorithm? (answer)
  • How to implement Bucket Sort in Java? (tutorial)
  • How to implement a Binary Search Algorithm without recursion in Java? (tutorial)
  • 50+ Data Structure and Algorithms Courses for Programmers (questions)

Thanks for reading this article. If you like this article then please share with your friends and colleagues. If you have any suggestion or feedback then please drop a comment.

P.S. — If you are serious about improving your Algorithms skills, I think the Data Structures and Algorithms: Deep Dive Using Java is the best one to start with.


By :javinpaul


Java Fundamentals: Learn Java for absolute beginners |Simpliv

Java Fundamentals: Learn Java for absolute beginners |Simpliv

Java Fundamentals: Learn Java for absolute beginners

Description
This is the best course to learn to program in Java in Spanish from scratch and without any experience in this fabulous programming language. This is the first course where we will study the Fundamentals of Java, and we will take you step by step until you acquire the bases of the Java language and you can start to study more advanced Java topics.

The content is divided into perfectly structured levels, each level supported by the previous one, with the aim of adding Java knowledge incrementally and so you can focus on mastering the issues little by little and gradually. So ensure the success of your Java training.

We will also offer support for any doubts about the didactic material included in this Java Fundamentals course.

We manage a new teaching methodology that we have called Speed ​​Learning. This methodology consists of concise videos that go directly to the point to be studied, complemented by eBooks with explanations and step-by-step images (which you can print, or search for any text you need, or use for your offline study), since As we know we can not do text search within a video. In addition, our methodology includes perfectly structured and very didactic exercises that will allow you to accelerate your eLearning learning. No loss of time in videos where you have to watch the instructor codify an exercise, too much theory, little practice or anything like that. Our Speed ​​Learning methodology guarantees that in the shortest possible time you will acquire the necessary knowledge for the Java professional and working world.

The Java Fundamentals course includes the following topics for study:

Lesson 1 - Starting with Java Technology

The amazing world of Java programming

What is Java technology (from a practical approach)

Our first Java program from scratch

Lesson 2 - Variables and Operators in Java

Use of Variables in Java and what we use them for

Types of Data in Java and how they are classified

Management and Classification of operators in Java

Lesson 3 - Control statements in Java

Using the if-else structure and where to use it

Handling the switch structure and when applying it

Lesson 4 - Handling Loops in Java

Use of the for loop and its use

Using the while loop and how to apply it

Use of the do-while loop and when to use it

Lesson 5 - Object Oriented Programming

Introduction to Object Oriented Programming (OOP)

Handling Classes in Java

Use of Objects in Java

Lesson 6 - Functions in Java

Declaration of Methods or Functions in Java

Use and call of functions in Java

Lesson 7 - Data Management in Java

Using Arrays in Java

Management of Matrices in Java

Lesson 8 - Inheritance in Java

Inheritance Management in Java

Use of superclasses and subclasses in Java

Final Level Laboratory

Final Exercise where everything learned in this Level is integrated

At the end you get a certificate of having completed the Java Fundamentals course.

We wait for you on the other side.

Ing. Ubaldo Acosta

Founder of Global Mentoring

Passion for Java Technology

Who this course is for:

Anyone who wants to learn how to program in Java
Basic knowledge
Basic knowledge of PC use
Basic management of an operating system such as Windows, Mac or Linux
It is not necessary to know how to program, we will start from scratch !!!
The attitude and desire to start coding and learning Java once and for all from scratch!
What will you learn
Have the basics of the programming language with Java
You will know the basic syntax of the Java language
Manage the concept of Variables and Operators in Java
We will study Object Oriented Programming with Java
You will learn the Control Statements and Loops in Java
We will see the concept of Functions with Java
We will study the concept of Inheritance in Java
We will learn to use Arrays in java
We will handle the concept of Matrices in Java
We will learn to Design Classes in Java
We will make a final application with everything learned in the course
To know more:

Java Essentials : Learn Core Java From Basic to Advance

Java Essentials : Learn Core Java From Basic to Advance

Learn Java Programming Using Practical Assignments. Start Building Back-end Web Applications Robust Test Automation Frameworks By End Of The Course. Learn More!

Description
This is only Java related course and it's great because it covers just the right amount of Java which is needed to leaning programming, java.

This is a comprehensive yet simple course on java programming language and it concentrates on Java programming concepts.

*************************** No Prior Coding Experience Needed ***************************

This course assumes that you have no programming background. If you have some experience then, it's just a bonus point. You have never code, have some experience or have a lot of experience any other programming language, this course is one stop place for you.

Java is one of the most and useful programming languages to learn You can build back-end of web applications and build robust test automation framework. Specially for Selenium WebDriver GUI automation, Java is most popular choice and has the largest community.

Each lecture consist of a video screencast and code files

There are quizzes, homework to test your knowledge

High focus on practice and asking questions

You will also learn coding best practices

Market is never short of jobs in Java programming language, there are ample of jobs in both Java development and Automation Testing using Java.

What are you waiting for? Enroll today and learn the powerful Java language !!!

Basic knowledge
Nothing else! It’s just you, your computer and your hunger to get started today
Java concepts are covered in the course, no experience needed
Windows/MAC computer
What will you learn
You will be able to EXPLAIN, DESIGN and IMPLEMENT efficient java Programs
You will be confident to clear test automation interviews
Understand the concepts of Object Oriented Programming Language
Complete understanding of java
Expert-level knowledge of Java code (+ advanced tips and tricks used by the pros)
Suitable for beginner programmers and ideal for users who learn faster when shown
To learn more:

Fundamental Data Structures & Algorithms in Java Programming | Simpliv

Fundamental Data Structures & Algorithms in Java Programming | Simpliv

Simpliv is aware that the animated, visual and spatial way is the best means to learn data structures and algorithms. This is why Simpliv’s course on data structures and algorithms is visual, adding fun and interactivity into your learning.

Description
This is an animated, visual and spatial way to learn data structures and algorithms

Our brains process different types of information differently - evolutionarily we are wired to absorb information best when it is visual and spatial i.e. when we can close our eyes and see it
More than most other concepts, Data Structures and Algorithms are best learnt visually. These are incredibly easy to learn visually, very hard to understand most other ways
This course has been put together by a team with tons of everyday experience in thinking about these concepts and using them at work at Google, Microsoft and Flipkart
What's Covered:

Big-O notation and complexity
Stacks
Queues
Trees
Heaps
Graphs and Graph Algorithms
Linked lists
Sorting
Searching
Using discussion forums

Please use the discussion forums on this course to engage with other students and to help each other out. Unfortunately, much as we would like to, it is not possible for us at Loonycorn to respond to individual questions from students:-(

We're super small and self-funded with only 2 people developing technical video content. Our mission is to make high-quality courses available at super low prices.

The only way to keep our prices this low is to NOT offer additional technical support over email or in-person. The truth is, direct support is hugely expensive and just does not scale.

We understand that this is not ideal and that a lot of students might benefit from this additional support. Hiring resources for additional support would make our offering much more expensive, thus defeating our original purpose.

It is a hard trade-off.

Thank you for your patience and understanding!

Who is the target audience?

Yep! Computer Science and Engineering grads who are looking to really visualise data structures, and internalise how they work
Yep! Experienced software engineers who are looking to refresh important fundamental concepts
Basic knowledge
Basic knowledge of programming is assumed, preferably in Java
What will you learn
Visualise - really vividly imagine - the common data structures, and the algorithms applied to them
Pick the correct tool for the job - correctly identify which data structure or algorithm makes sense in a particular situation
Calculate the time and space complexity of code - really understand the nuances of the performance aspects of code
To continue: