{"id":1283,"date":"2016-07-16T05:58:43","date_gmt":"2016-07-16T05:58:43","guid":{"rendered":"http:\/\/www.testingdocs.com\/questions\/?p=1283"},"modified":"2024-08-09T03:50:08","modified_gmt":"2024-08-09T03:50:08","slug":"write-a-java-program-for-binary-search","status":"publish","type":"post","link":"https:\/\/www.testingdocs.com\/questions\/write-a-java-program-for-binary-search\/","title":{"rendered":"Write a Java Program for Binary Search? [ 2024 ]"},"content":{"rendered":"<h2>Write a Java Program for Binary Search?<\/h2>\n<p>In this tutorial, we will write a Java program to implement Binary Search.\u00a0<b>BS<\/b>\u00a0is faster than sequential <b>search<\/b>. The requirement for BS\u00a0is that the array should be sorted in a particular order before searching.<\/p>\n<h3>Divide and Conquer<\/h3>\n<p>Assume that searchItem that needs to be searched and array sorted in ascending order. We will find the middle of the array and compare with searchItem.<\/p>\n<p>If searchItem is greater than the middle item of the array then <b>search<\/b> the right half of the array. If the searchItem is less than the middle item, then <b>search<\/b> the left half array.<\/p>\n<h3><strong>Flow Chart<\/strong><\/h3>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-232 size-full\" src=\"http:\/\/www.testingdocs.com\/questions\/wp-content\/uploads\/Binary-Search-Flow-Chart-768x1087.png\" alt=\"\" width=\"768\" height=\"1087\" title=\"\" srcset=\"https:\/\/www.testingdocs.com\/questions\/wp-content\/uploads\/Binary-Search-Flow-Chart-768x1087.png 768w, https:\/\/www.testingdocs.com\/questions\/wp-content\/uploads\/Binary-Search-Flow-Chart-768x1087-212x300.png 212w, https:\/\/www.testingdocs.com\/questions\/wp-content\/uploads\/Binary-Search-Flow-Chart-768x1087-723x1024.png 723w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/p>\n<p>&nbsp;<\/p>\n<h3><strong>Binary Search Java program<\/strong><\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">import java.util.Arrays;\r\nimport java.util.InputMismatchException;\r\nimport java.util.Scanner;\r\n\r\npublic class BinarySearchExample {\r\n    public static void main(String[] args) {\r\n        int n;\r\n        Scanner input = null;\r\n        int[] a = null;\r\n        int searchItem,low,high;\r\n        try {\r\n            input=new Scanner(System.in);\r\n            System.out.println(\"Enter size of the array:\");\r\n            n= input.nextInt();\r\n\r\n            if(n &gt; 0) {\r\n                a=new int[n];\r\n                System.out.println(\"Enter array elements:\");\r\n                for (int i = 0; i &lt; n; i++) {\r\n                    a[i] = input.nextInt();\r\n                }\r\n            }else{\r\n                System.out.println(\"Enter positive number.\");\r\n                System.exit(0);\r\n            }\r\n\r\n            System.out.println(\"Input Unsorted Array is:\");\r\n            printArray(a);\r\n\r\n            System.out.println(\"Enter the search item\");\r\n            searchItem =input.nextInt();\r\n            Arrays.sort(a);\r\n\r\n            System.out.println(\"Input Sorted Array is:\");\r\n            printArray(a);\r\n\r\n            System.out.println(\"Performing Binary search for:\"+ searchItem);\r\n\r\n            low=0;\r\n            high=a.length-1;\r\n\r\n            while(high &gt;= low) {\r\n                int mid = (high+low)\/2;\r\n                if(a[mid] == searchItem){\r\n                    System.out.println(\"Item found at:\" + mid );\r\n                    System.exit(0);\r\n                }\r\n\r\n                else if(a[mid] &lt; searchItem) {\r\n                    low = mid + 1;\r\n                }\r\n                else {\r\n                    high = mid - 1;\r\n                }\r\n            }\r\n\r\n        }catch (InputMismatchException ime) {\r\n            System.out.println(\"Not a valid input\");\r\n        }\r\n        catch (Exception e) {\r\n            e.printStackTrace();\r\n        } finally\r\n        {\r\n            if(input!=null)\r\n            {input.close();}\r\n        }\r\n    }\r\n\r\n    private static void printArray(int[] a){\r\n        for (int aA : a) {\r\n            System.out.print(\"[ \" + aA + \" ]\");\r\n        }\r\n        System.out.println( \"\");\r\n    }\r\n\r\n}<\/pre>\n<p>&nbsp;<\/p>\n<h3><strong>Run output of the program<\/strong><\/h3>\n<p>Save the program in the IDE and execute the program.<\/p>\n<p>User Input for the program:<\/p>\n<p>Enter the size of the array. The program prompts for array elements. Enter the array elements.<\/p>\n<p>The program then prompts the user to enter the search item.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-1280\" src=\"http:\/\/www.testingdocs.com\/questions\/wp-content\/uploads\/Binary-Search-Java-Program.png\" sizes=\"auto, (max-width: 1134px) 100vw, 1134px\" alt=\"Binary Search Java Program\" width=\"1134\" height=\"685\" title=\"\"><\/p>\n<p>Enter size of the array:<br \/>\n7<br \/>\nEnter array elements:<br \/>\n23<br \/>\n56<br \/>\n9<br \/>\n103<br \/>\n77<br \/>\n99<br \/>\n14<br \/>\nInput Unsorted Array is:<br \/>\n[ 23 ][ 56 ][ 9 ][ 103 ][ 77 ][ 99 ][ 14 ]<br \/>\nEnter the <b>search<\/b> item<br \/>\n77<br \/>\nInput Sorted Array is:<br \/>\n[ 9 ][ 14 ][ 23 ][ 56 ][ 77 ][ 99 ][ 103 ]<br \/>\nPerforming <b>Binary<\/b> <b>search<\/b> for:77<br \/>\nItem found at:4<\/p>\n<h2>Java Tutorials<\/h2>\n<p>Java Tutorial on this website:<\/p>\n<ul>\n<li><a href=\"https:\/\/www.testingdocs.com\/java-tutorial\/\">https:\/\/www.testingdocs.com\/java-tutorial\/<\/a><\/li>\n<\/ul>\n<p>For more information on Java, visit the official website :<\/p>\n<ul>\n<li><a href=\"https:\/\/www.oracle.com\/in\/java\/\" rel=\"noopener\">https:\/\/www.oracle.com\/in\/java\/<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Write a Java Program for Binary Search? In this tutorial, we will write a Java program to implement Binary Search.\u00a0BS\u00a0is faster than sequential search. The requirement for BS\u00a0is that the array should be sorted in a particular order before searching. Divide and Conquer Assume that searchItem that needs to be searched and array sorted in [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[18],"tags":[24],"class_list":["post-1283","post","type-post","status-publish","format-standard","hentry","category-java-programs","tag-java-programs","has-post-title","has-post-date","has-post-category","has-post-tag","has-post-comment","has-post-author",""],"_links":{"self":[{"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/posts\/1283","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/comments?post=1283"}],"version-history":[{"count":9,"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/posts\/1283\/revisions"}],"predecessor-version":[{"id":23603,"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/posts\/1283\/revisions\/23603"}],"wp:attachment":[{"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/media?parent=1283"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/categories?post=1283"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.testingdocs.com\/questions\/wp-json\/wp\/v2\/tags?post=1283"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}