32.8k views
1 vote
write a 〕ava program to sort a random list of 10 numbers entered b y user in an array using Selection Sort technique

User Yosep Tito
by
7.5k points

1 Answer

5 votes

Here is code in java to perform selection sort.

// import library

import java.util.*;

import java.lang.*;

import java.io.*;

class Solution

{

public static void main (String[] args) throws java.lang.Exception

{

try{

// creating object of Solution class

Solution obj=new Solution();

// creating object of Scanner class to read input

Scanner sc=new Scanner(System.in);

// create array of size 10

int arr[]=new int[10];

System.out.println("Please Enter 10 numbers :");

// reading input from user

for(int i=0;i<10;i++)

{

arr[i]=sc.nextInt();

}

// calling sort_fun with object "obj" to sort array

obj.sort_fun(arr);

// printing the array after selection sort

System.out.println("Array after performing selection sort:");

for (int i=0; i<10; ++i)

System.out.print(arr[i]+" ");

System.out.println();

}catch(Exception ex){

return;}

}

// creating function to perform selection sort

public static void sort_fun(int arr[])

{

for (int i = 0; i < 10-1; i++)

{

int m_idx = i;

for (int j = i+1; j < 10; j++)

if (arr[j] < arr[m_idx])

m_idx = j;

// find the minimum element and put them in the beginning

int temp = arr[m_idx];

arr[m_idx] = arr[i];

arr[i] = temp;

}

}

}

Step-by-step explanation:

First create an object of "Solution" class. Then create an object of "Scanner" class to read input from user.After this create an array of size 10 of type integer and read 10 value from user in the array.In the sort_fun(),it will find the smallest element of unsorted array and put it in the beginning of the array. Then it find the second smallest number and put it after the first element. Similarly it will find the next element and put it after second element.When the loop end, the array will be sorted.

Output:

Please Enter 10 numbers :

45 34 12 90 84 1 4 56 12 6

Array after performing selection sort:

1 4 6 12 12 34 45 56 84 90

User Daniel Majano
by
8.7k points