Selection Sort [codingblocks]

Take as input N, the size of array. Take N more inputs and store that in an array. Write a function that selection sorts the array. Print the elements of sorted array.


1.It reads a number N.
2.Take Another N numbers as input and store them in an Array.
3.Sort the array using Selection Sort and print that Array.

Input Format

Constraints

N cannot be Negative. Range of Numbers can be between -1000000000 to 1000000000.

Output Format

Sample Input

4
2
-18
45
30

Sample Output

-18
2
30
45

Explanation

Write selection sort to sort the given integers in the problem.

Java Code:



/*
Amit Kumar
04-12-2020
IDE Code: https://ide.geeksforgeeks.org/FHfdCyblZ4
*/

package array;
import java.util.Scanner;

public class Array_SelectionSort {
    public static Scanner scanner = new Scanner(System.in);
    public static void main(String [] args) {
        int arrSize = scanner.nextInt();
        int [] arr = new int[arrSize];
        for (int i=0; i<arrSize; i++) {
            arr[i] = scanner.nextInt();
        }

        selectionSort(arr);

        for (int value : arr) {
            System.out.println(value);
        }
    }

    public static void selectionSort(int[] arr) {
        for (int i=0; i<arr.length-1; i++) {
            int currMin = i;
            for (int j=i+1; j<arr.length; j++) {
                if (arr[currMin] > arr[j])
                    currMin = j;
            }
            if (currMin != i){
                int temp = arr[i];
                arr[i] = arr[currMin];
                arr[currMin] = temp;
            }
        }
    }
}

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )