Q-22: Write a JAVA program to create your own package and use it in your program.
  

Main


// Contributed by - Anuj Das ( GC College, Silchar - @ Department of Computer Science ) import java.util.Scanner; import Search.unsorted.LinearSearch; import Search.sorted.BinarySearch; class MyOwnPackage { static void display(int arr[ ]) { for(int i=0; i < arr.length; i++) { System.out.print(arr[i]+" "); } System.out.println(""); } public static void main(String[ ] args) { Scanner sc = new Scanner(System.in); LinearSearch ls = new LinearSearch(); BinarySearch bs = new BinarySearch(); // Performing Linear Search on unsorted array System.out.println("LINEAR SEARCH:"); int unsorted_arr[ ] = {32, 45, 55, 21, 87, 67, 34}; display(unsorted_arr); int x = 21; ls.LinearSearch(unsorted_arr,x); System.out.println("\n"); // Performing Binary Search on sorted array System.out.println("BINARY SEARCH:"); int sorted_arr[ ] = {10, 14, 18, 34, 45, 56, 78}; display(sorted_arr); int y = 28; bs.BinarySearch(sorted_arr,y); } }

OUTPUT

cmd->  javac  MyOwnPackage.java
cmd->  java  MyOwnPackage

LINEAR SEARCH:
32  45  55  21  87  67  34
21 found at position 4


BINARY SEARCH:
10  14  18  34  45  56  78
28 not found in this array!

   
  

Search / unsorted /


// Contributed by - Anuj Das ( GC College, Silchar - @ Department of Computer Science ) package Search.unsorted; public class LinearSearch { public void LinearSearch(int[ ] arr, int x) { for(int i=0; i < arr.length; i++) { if(arr[i]==x) { System.out.println(x + " found at position "+(i+1)); return; } } System.out.println(x + " not found in this array!"); } }
  

Search / sorted /


// Contributed by - Anuj Das ( GC College, Silchar - @ Department of Computer Science ) package Search.sorted; public class BinarySearch { public void BinarySearch(int[ ] arr, int x) { int beg=0, end=(arr.length -1); int mid = (int)(beg+end)/2; while(beg <= end && arr[mid] != x) { if(x < arr[mid]) end = mid-1; else beg = mid+1; mid = (int)((beg+end)/2); } if(arr[mid] == x) System.out.println(x +" found at position " + (mid+1)); else System.out.println(x +" not found in this array!"); } }