Facebook
From Bistre Cat, 1 Year ago, written in Java.
This paste is a reply to Selection Sort from Sukruth Surendra NS - view diff
Embed
Download Paste or View Raw
Hits: 173
  1. import java.util.*;
  2.  
  3. public class Main
  4. {
  5.         public static void main(String[] args) {
  6.             Scanner sc = new Scanner(System.in);
  7.                 int n = sc.nextInt();
  8.                 int arr[] = new int[n];
  9.                 for (int i = 0 ; i < n ;i++ )
  10.                 {
  11.                     arr[i] = sc.nextInt();
  12.                 }
  13.                 //Selection sort
  14.                 for(int i = 0; i < n-1 ; i++)
  15.                 {
  16.                     int minidx = i;
  17.                    
  18.             for(int j = i+1 ; j < n ; j++)
  19.             {
  20.                 if (arr[j] < arr[minidx])
  21.                 {
  22.                     minidx = j;
  23.                 }
  24.                // swap
  25.                 int temp = arr[minidx];
  26.                 arr[minidx] = arr[i];
  27.                 arr[i] = temp;
  28.                
  29.             }
  30.                
  31.                 }
  32.                 System.out.print(Arrays.toString(arr));
  33.         }
  34. }
  35.  
  36. 2 type
  37.   import java.util.*;
  38.  
  39. public class Main
  40. {
  41.         public static void main(String[] args) {
  42.             Scanner sc = new Scanner (System.in);
  43.                 int n = sc.nextInt();
  44.                 int arr [] = new int [n];
  45.                 for (int i = 0;i < n ;i++ )
  46.                 {
  47.                     arr[i] = sc.nextInt();
  48.                 }
  49.                
  50.                 System.out.println(selectionSort(arr,n));
  51.         }
  52.        
  53.         public static String selectionSort(int arr [],int n)
  54.         {
  55.             for(int i = 0; i < n-1; i++)
  56.             {
  57.                 int minNum = minInArr(arr,i);
  58.                 //swap
  59.                 int temp = arr[minNum];
  60.                 arr[minNum] = arr[i];
  61.                 arr[i] = temp;
  62.             }
  63.            return(Arrays.toString(arr));
  64.         }
  65.        
  66.         public static int minInArr(int arr[],int i)
  67.         {
  68.             int minidx = i;
  69.             for(int j = i+1 ; j < arr.length ; j++)
  70.             {
  71.                 if (arr[j] < arr[minidx])
  72.                 {
  73.                     minidx = j;
  74.                 }
  75.             }
  76.             return minidx;
  77.         }
  78. }