Advertisement
mrScarlett

Selection Sort

Aug 29th, 2017
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.92 KB | None | 0 0
  1. import java.util.Arrays;
  2. public class SelectionSort
  3. {
  4.     public static void main (String args []){
  5.         System.out.println("\f");
  6.         selectionSort();  
  7. }
  8. public static void selectionSort() {
  9.     int [] nums = {22,11,9,6,3,2,1};
  10.     for (int i = 0; i < nums.length-1; i++) {
  11.         int minIndex = i;      // Assumed index of smallest remaining value.
  12.         for (int j = i+1; j < nums.length; j++) {
  13.             if (nums[j] < nums[minIndex] ) {
  14.                 minIndex = j;  // Remember index of new minimum
  15.             }
  16.         }
  17.         if (minIndex != i) {
  18.             //Exchange current element with smallest remaining.
  19.              //But note that this only happens once each outer loop iteration, at the end of the inner loop's looping
  20.             int temp = nums[i];
  21.             nums[i] = nums[minIndex];
  22.             nums[minIndex] = temp;
  23.         }
  24.         System.out.println(Arrays.toString(nums));
  25.     }
  26. }
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement