Binary Search & Bubble Sort Implementation

import java.util.Scanner;
public class Main {
 public static void main(String[]args) {
  int arr[] = {20, 50, 40, 30, 10};
  int key;
  //printing the list as it is.
  System.out.println("Unsorted Array: ");
  for (int i = 0; i < arr.length; i++) {
   System.out.print(" " + arr[i]);
  }
  System.out.println();
  
  //instantiating BubbleSort class with object s1.
  BubbleSort s1 = new BubbleSort();
  //calling sort function to sort the elements.
  s1.sort(arr);
  //printing the sorted array.
  System.out.println("Sorted Array: ");
  for (int i = 0; i < arr.length; i++) {
   System.out.print(" " + arr[i]);
  }
  System.out.println();
  
  //asking user for search element.
  Scanner input = new Scanner(System.in);
  System.out.print("Enter element you want to search: ");
  key = input.nextInt();

  //initialising l and h meaning highest and lowest index in array.
   int l = 0;
   int h = arr.length - 1;
  
  //instantiating BiSearch class to implement Binary search.  
   BiSearch b = new BiSearch();
  //calling search function to search the key element and storing it in res. 
   int res = b.search(l,h,key, arr);
  // printing key element and its index according to sorted arrary list.
  if(res == 0 || res == -1){
   System.out.println("Key not found");
   return;
   }else{ 
   System.out.println("key: "+key+ " found at index: "+res);
  }
 }
}

// BubbleSort class to sort elements
class BubbleSort {
 public void sort(int arr[]) {
  for (int i = 0; i < arr.length; i++) {
   for (int j = 0; j < arr.length - 1; j++) {
    if (arr[j] > arr[j + 1]) {
     int temp = arr[j];
     arr[j] = arr[j + 1];
     arr[j + 1] = temp;
    }
   }
  }
 }
}

// BiSearch class for Binary Searching Method.
class BiSearch {
 public int search(int l, int h, int key, int arr[]) {
  if(l>h){
      return -1;
      }
  if (l == h) {
   if (arr[l] == key) {
    return l;
   } else {
    return 0;
   }
  } else {
   int mid = (l + h) / 2;
   if (arr[mid] == key) {
    return mid;
   }
   if (arr[mid] < key) {
 // recursively search rhs half of array start from next of mid element to last/high element.
    return search(mid + 1, h, key, arr);
   } else {
 // recursively search lhs half of array start from first/low element to one element before mid  
    return search(l, mid - 1, key, arr);
   }
  }
 }
}

Comments

Popular posts from this blog

AI and Human Evolution

To Do List App (GUI) using C#

Snake Game using JAVA