Advertisement
Guest User

Untitled

a guest
Feb 28th, 2020
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. package com.chrisstubbs;
  2.  
  3. import java.util.Arrays;
  4.  
  5. public class Main {
  6.  
  7. public static void main(String[] args) {
  8. //initialize the array
  9. int[] arr = {10, 6, 90, 77, 65, 7, 9, 94};
  10. //linear search will return true since 9 is present in the array
  11. search(arr, 9);
  12.  
  13. //initialize another array
  14. int[] arr2 = {20, 4, 22, 109, 87, 99, 100, 2};
  15. //sort the array
  16. Arrays.sort(arr2);
  17. //binary search will return false since 101 is not present
  18. binarySearch(arr2, 101);
  19.  
  20.  
  21. }
  22.  
  23. //this search loops through the entire array to search for the key
  24. public static boolean search(int[] array, int key) {
  25. for (int i = 0; i < array.length; i++) {
  26. if (array[i] == key) {
  27. return true;
  28. }
  29. }
  30.  
  31. return false;
  32. }
  33.  
  34. //this search uses a binary search to search for the key
  35. public static boolean binarySearch(int[] arr, int key) {
  36. int l = 0;
  37. int r = arr.length - 1;
  38.  
  39. while (l <= r) {
  40. int m = l + (r - l) / 2;
  41. // Check if x is present at mid
  42. if (arr[m] == key) {
  43. return true;
  44. }
  45. // If x greater, ignore left half
  46. if (arr[m] < key) {
  47. l = m + 1;
  48. }
  49. // If x is smaller, ignore right half
  50. else {
  51. r = m - 1;
  52. }
  53. }
  54. // if we reach here, then element was not present
  55. return false;
  56. }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement