Advertisement
Guest User

Selection Sort

a guest
Dec 4th, 2016
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.28 KB | None | 0 0
  1. //UIUC CS125 FALL 2014 MP. File: SelectionSort.java, CS125 Project: Challenge7-RecursiveKnight, Version: 2014-11-24T10:49:46-0600.714066947
  2. /**
  3.  *
  4.  * @author johri3
  5.  *
  6.  */
  7. public class SelectionSort {
  8.     /**
  9.      * Sorts the entire array using selection sort
  10.      * This is just a wrapper method that calls the
  11.      * recursive method with the correct parameter lo,hi values.
  12.      * @param data
  13.      */
  14.     public static void sort(double[] data) {
  15.         sort(data, 0, data.length-1);
  16.     }
  17.  
  18.     /** Recursively sorts the sub array lo...hi using selection sort algorithm.*/
  19.     public static void sort(double[] data, int lo, int hi) {
  20.         if (lo < hi)
  21.         {
  22.             swap(data, lo, findMin(data, lo, hi));
  23.             sort(data, lo+1, hi);
  24.         }
  25.     }
  26.  
  27.     /** Helper method for selection sort: Swaps values at indices i and j*/
  28.     public static void swap(double[] data, int i, int j) {
  29.         double temp = data[i];
  30.         data[i] = data[j];
  31.         data[j] = temp;
  32.     }
  33.  
  34.     /**
  35.      * Recursively finds the position of the smallest value of the values lo...hi (inclusive).
  36.      * @param data
  37.      * @param lo
  38.      * @param hi
  39.      * @return
  40.      */
  41.     public static int findMin(double[] data, int lo, int hi) {
  42.         int best = lo;
  43.         if(lo < hi)
  44.         {
  45.             int temp = findMin(data, lo+1, hi);
  46.             if(data[temp] < data[best])
  47.                 best = temp;
  48.         }
  49.         return best;
  50.     }
  51.  
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement