// 12/9/2019

/** 
 * Selection Sort
 * Notice the similarity to the code for finding duplicates in an unsorted array
  */
public class SelectionSort {
  public static void main(String[] args) {
   
    int[] numbers = {72, 5, 61,54, 11, 5, 3, 18, 5};
    
    // outer loop places min at loc i
    for (int i=0; i<numbers.length-1; i++) {
      // inner loop searches for min and swaps
      for (int j=i+1; j<numbers.length; j++) {
        if (numbers[j] < numbers[i]) {
          // swap them
          System.out.println("swapping: " + numbers[i] + " and " + numbers[j]);
          int temp = numbers[i];
          numbers[i] = numbers[j];
          numbers[j] = temp;
        }
      }
    }
    System.out.println("Sorted Array:");
    for (int num: numbers)
      System.out.print(num + " ");
    System.out.println();
    System.out.println("search for 5 " + binarySearch(numbers, 5));
    System.out.println("search for 44 " + binarySearch(numbers, 44));
  }
  
  // binary search
  public static boolean binarySearch(int[] arr, int key)  {
    
    int beg=0; 
    int end=arr.length-1;
    int mid;
    
    while (beg<=end) {
      // calculate index of middle element
      mid = (beg+end)/2;
      
      if (key < arr[mid]) {
        end=mid-1;
      }
      else if (key > arr[mid]) {
        beg=mid+1;
      }
      else // ==
        return true;
    }
    return false;
  }
      
      
      
    
    
    
  
  
  
  
  
  
}