Q:

Java program to sort an array in ascending order using selection sort

belongs to collection: Java Array Programs

0

Java program to sort an array in ascending order using selection sort

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this program, we will create an array of integers then we will sort an array element in ascending order using selection sort.

In the Selection Sort technique, we find the smallest element and swap the smallest elements with the corresponding element to sort into ascending order.

Program/Source Code:

The source code to sort an array in ascending order using selection sort is given below. The given program is compiled and executed successfully.

// Java program to sort an array in ascending order 
// using selection sort

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner SC = new Scanner(System.in);

    int i = 0;
    int j = 0;
    int t = 0;
    int min = 0;

    int arr[] = {14, 49, 79, 87, 78};

    //Sort created array.
    while (i < 5) {
      min = i;
      j = i + 1;

      while (j < 5) {
        if (arr[j] < arr[min])
          min = j;
        j = j + 1;
      }

      t = arr[i];
      arr[i] = arr[min];
      arr[min] = t;

      i = i + 1;
    }

    System.out.println("Sorted Array in ascending order: ");

    i = 0;
    while (i < 5) {
      System.out.print(arr[i] + " ");
      i = i + 1;
    }
  }
}

Output:

Sorted Array in ascending order: 
14 49 78 79 87

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Array Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to sort an array in descending order ... >>
<< Java program to search an item in an array using i...