coolbud012

SelectionSort

Oct 22nd, 2015
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.07 KB | None | 0 0
  1. package chapter_3_sorting;
  2.  
  3. import java.util.Arrays;
  4.  
  5. /**
  6.  * Pseudocode for Selection Sort
  7.  * @author shivamchopra
  8.  *
  9.  *
  10.  *   for i = 0 to Array.length - 2
  11.  *   minIndex = i;
  12.  *   for j = i + 1 to Array.length - 1
  13.  *   if(data[j] < data[minIndex])
  14.  *   minIndex = j
  15.  *   temp = data[minIndex]
  16.  *   data[minIndex] = data[i]
  17.  *   data[i] = temp;
  18.  *
  19.  */
  20.  
  21. public class SelectionSorting {
  22.    
  23.     public static void main(String[] args) {
  24.         int[] numbers = { 1, 5, 2, 8, 2, 9, 10, 32, 3 };
  25.         System.out.println("Unsorted Array : " + Arrays.toString(numbers));
  26.         SelectionSorting sorting = new SelectionSorting();
  27.         sorting.sort(numbers);
  28.         System.out.println("Sorted Array : " + Arrays.toString(numbers));
  29.     }
  30.    
  31.    
  32.     public void sort(int[] numbers) {
  33.         int minIndex = 0;
  34.         for(int i = 0; i < numbers.length - 1; i++) {
  35.             minIndex = i;
  36.             for(int j = i + 1; j < numbers.length; j++) {
  37.                 if(numbers[j] < numbers[minIndex]) {
  38.                     minIndex = j;
  39.                     int temp = numbers[minIndex];
  40.                     numbers[minIndex] = numbers[i];
  41.                     numbers[i] = temp;
  42.                 }
  43.             }
  44.         }
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment