Advertisement
bzhang22

Untitled

Apr 25th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.61 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. public class Searches {
  4.  
  5.     public static void sequentialSearch(int[] arr, int target){
  6.         for (int i : arr){
  7.             if (i == target)
  8.                 System.out.println("Found");
  9.         }
  10.         System.out.println("Not found");
  11.     }
  12.  
  13.     public static void binarySearch(int[] arr, int target){
  14.         int left = 0, right = arr.length - 1;
  15.         while (left <= right){
  16.             int middle = (left + right) / 2;
  17.             if (arr[middle] < target)
  18.                 left = middle + 1;
  19.             else if(arr[middle] > target)
  20.                 right = middle - 1;
  21.             else //the case when target equals the middle value
  22.                 System.out.println("Found");
  23.         }
  24.         System.out.println("Not found");
  25.  
  26.  
  27.  
  28.     }
  29.  
  30.     public static void selectionSort(int[] array) {
  31.         // Select
  32.         for (int i = 0; i < array.length - 1; i++) {
  33.             // We're searching the correct value at index i
  34.             int indexOfMin = i;
  35.             for (int j = i + 1; j < array.length; j++) {
  36.                 if (array[j] < array[indexOfMin]) {
  37.                     indexOfMin = j;
  38.                 }
  39.             }
  40.             // Swap
  41.             int temp = array[indexOfMin];
  42.             array[indexOfMin] = array[i];
  43.             array[i] = temp;
  44.         }
  45.     }
  46.  
  47.     public static void main(String[] args){
  48.  
  49.         int[] x = {2, 3, 4, 1, 6, 5, 7};
  50.         //sequentialSearch(x, 6);
  51.         int[] y = {2, 3, 4, 5, 6};
  52.         //binarySearch(y, 5);
  53.  
  54.         selectionSort(x);
  55.         System.out.println(Arrays.toString(x));
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement