जावा प्रोग्राम द्विआधारी खोज एल्गोरिदम को लागू करने के लिए

इस उदाहरण में, हम जावा में द्विआधारी खोज एल्गोरिदम को लागू करना सीखेंगे।

इस उदाहरण को समझने के लिए, आपको निम्नलिखित जावा प्रोग्रामिंग विषयों का ज्ञान होना चाहिए:

  • जावा जबकि और करते हैं … जबकि लूप
  • जावा अगर … और स्टेटमेंट
  • जावा एरेस

उदाहरण: बाइनरी खोज एल्गोरिथम को लागू करने के लिए जावा प्रोग्राम

 import java.util.Scanner; // Binary Search in Java class Main ( int binarySearch(int array(), int element, int low, int high) ( // Repeat until the pointers low and high meet each other while (low <= high) ( // get index of mid element int mid = low + (high - low) / 2; // if element to be searched is the mid element if (array(mid) == element) return mid; // if element is less than mid element // search only the left side of mid if (array(mid) < element) low = mid + 1; // if element is greater than mid element // search only the right side of mid else high = mid - 1; ) return -1; ) public static void main(String args()) ( // create an object of Main class Main obj = new Main(); // create a sorted array int() array = ( 3, 4, 5, 6, 7, 8, 9 ); int n = array.length; // get input from user for element to be searched Scanner input = new Scanner(System.in); System.out.println("Enter element to be searched:"); // element to be searched int element = input.nextInt(); input.close(); // call the binary search method // pass arguments: array, element, index of first and last element int result = obj.binarySearch(array, element, 0, n - 1); if (result == -1) System.out.println("Not found"); else System.out.println("Element found at index " + result); ) )

आउटपुट 1

 खोजा जाने वाला तत्व दर्ज करें: 6 सूचकांक 3 में पाया गया तत्व

यहां, हमने उपयोगकर्ता से इनपुट लेने के लिए जावा स्कैनर क्लास का उपयोग किया है। उपयोगकर्ता से इनपुट के आधार पर, हमने यह जांचने के लिए द्विआधारी खोज का उपयोग किया कि क्या तत्व सरणी में मौजूद है।

हम उसी कार्य को करने के लिए पुनरावर्ती कॉल का भी उपयोग कर सकते हैं।

  int binarySearch(int array(), int element, int low, int high) ( if (high>= low) ( int mid = low + (high - low) / 2; // check if mid element is searched element if (array(mid) == element) return mid; // Search the left half of mid if (array(mid)> element) return binarySearch(array, element, low, mid - 1); // Search the right half of mid return binarySearch(array, element, mid + 1, high); ) return -1; )

यहां, विधि binarySearch()स्वयं को बुला रही है जब तक कि तत्व नहीं मिलता है या, ifस्थिति विफल हो जाती है।

यदि आप द्विआधारी खोज एल्गोरिथ्म के बारे में अधिक जानना चाहते हैं, तो द्विआधारी खोज एल्गोरिदम पर जाएं।

दिलचस्प लेख...