Menu Close

Selection Sorting in Java …fcukthecode

Sort the given set of numbers using Selection Sort.

The first line of the input contains the number of elements,
The second line of the input contains the numbers to be sorted.
In the output print the final sorted array in the given format.

Input:
No: of Elements:  5
Enter the Elements:  25 47 11 65 1

Output:
Sorted Array:
1 11 25 47 65
import java.io.*;
import java.util.*;
class selectsort
{
  void sort(int array[],int size)
  {
    for (int i = 0; i < size-1; i++)
    {
      int min_element = i;
      for (int j = i+1; j < size; j++)
        if (array[j] < array[min_element])
          min_element = j;
      int temp = array[min_element];
      array[min_element] = array[i];
      array[i] = temp;
    }
  }

  void printy(int array[],int size)
  {
    int n = array.length;
    for (int i=0; i<size; ++i)
    System.out.print(array[i]+" ");
    System.out.println();
  }

  public static void main(String args[])
  {
    int size, i;
    int arr[] = new int[50];
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter Size of Array:  ");
    size = scan.nextInt();

    System.out.print("Enter the Array:  ");
    for(i=0; i<size; i++)
    {
      arr[i] = scan.nextInt();
    }

    selectsort sorty = new selectsort();
    sorty.sort(arr,size);
    System.out.println("Sorted array");
    sorty.printy(arr,size);
  }
}

INPUT_1:
Enter Size of Array:  5
Enter the Array:  25  47  11  65  1

OUTPUT:
Sorted array
1  11  25  47  65


INPUT_2:
Enter Size of Array: 6
Enter the Array:  101  007  005  2  65  120

OUTPUT:
Sorted array
2  5  7  65  101  120


INPUT_3:
Enter Size of Array: 3
Enter the Array:  99  101  111

OUTPUT:
Sorted array
99  101  111


INPUT_4:
Enter Size of Array:  2
Enter the Array:  45  54

OUTPUT:
Sorted array
45  54


INPUT_5:
Enter Size of Array:  10
Enter the Array:  1  10  11  111  25  101  999  56  845  52

OUTPUT:
Sorted array
1  10  11  25  52  56  101  111  845  999


INPUT_6:
Enter Size of Array:  8
Enter the Array:  65  45  78  96  81  72  57  22

OUTPUT:
Sorted array
22  45  57  65  72  78  81  96


ILLUSTRATION

Executed using javac on terminal linux