Advertisement
gelita

Selection Sort

Feb 17th, 2020
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.03 KB | None | 0 0
  1. /**
  2.  *  Selection Sort
  3.  *
  4.  *  Prompt:    Given an unsorted array of integers, return the array sorted
  5.  *             using selection sort.
  6.  *
  7.  *  Input:     input {Array}
  8.  *  Output:    {Array}
  9.  *
  10.  *  Example:   [3,9,1,4,7] --> [1,3,4,7,9]
  11.  *
  12.  */
  13.  
  14. import java.util.*;
  15.  
  16. class BasicSort {
  17.  
  18.       public static void main(String[] args){
  19.         int[] arr = {3,9,1,4,7};
  20.         System.out.println(Arrays.toString(selection(arr)));
  21.       }
  22.  
  23.       public static int[] selection(int[] input) {
  24.         int len = input.length;
  25.         int currMin;
  26.         for(int lastSorted = 0; lastSorted < len -1; lastSorted++){
  27.           currMin = lastSorted;
  28.           //start comparisons at after the lastSorted element
  29.           for(int i = lastSorted + 1; i < len; i++){
  30.             if(input[i] < input[currMin]){
  31.               currMin = i;
  32.             }
  33.           }
  34.           int temp = input[currMin];
  35.           input[currMin] = input[lastSorted];
  36.           input[lastSorted] = temp;
  37.         }
  38.       return input;
  39.       }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement