m2skills

selection java

Apr 7th, 2017
867
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.58 KB | None | 0 0
  1. /*program to perform selection sort on an array*/
  2. import java.util.Scanner;
  3. import java.io.*;
  4.  
  5. import static java.lang.System.*;
  6.  
  7. /**
  8.  * Created by MOHIT on 31-12-2016.
  9.  */
  10. public class select {
  11.     public static void main(String arg[]) {
  12.         Scanner sc  = new Scanner(in);
  13.        
  14.         System.out.print("Enter the Array to be sorted : ");
  15.         String str1 = sc.next();
  16.        
  17.         String[] strArr = str1.split(",");
  18.         int[] numbers = new int[strArr.length];
  19.        
  20.         int i=0;
  21.         for (String str2 :strArr) {
  22.             int temp = Integer.parseInt(str2);
  23.             numbers[i] = temp;
  24.             i++;
  25.         }
  26.        
  27.         numbers = selectionSort(numbers);
  28.  
  29.         System.out.println("The Array after sorting is : ");
  30.         for(i=0; i<numbers.length; i++){
  31.             System.out.print(numbers[i] + " ");
  32.         }
  33.     }
  34.    
  35.     // method that sorts the vector using selection sort
  36.     private static int[] selectionSort(int[] numbers) {
  37.         int temp;
  38.        
  39.         // loop i from 0 to n-1
  40.         // assign minimum element Index as i initially
  41.         for(int i=0; i< numbers.length-1; i++){
  42.             int minIndex = i;
  43.             // loop j from i+1 to n
  44.             // compare jth element to minIndex element
  45.             for(int j=i+1; j<numbers.length-1; j++){
  46.                 if(numbers[minIndex]> numbers[j]){
  47.                     minIndex = j;
  48.                 }
  49.             }
  50.            
  51.             // swap the smallest element to the minIndex position
  52.             temp = numbers[minIndex];
  53.             numbers[minIndex] = numbers[i];
  54.             numbers[i] = temp;
  55.         }
  56.        
  57.         // return sorted array
  58.         return numbers;
  59.     }
  60. }
Add Comment
Please, Sign In to add comment