Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Friday, November 6, 2020

Selection Sort in java with Algorithm, Example

Selection Sort in java

In this tutorial, We will learn about another sorting technique where auxiliary space is minimized. As of now we have discussed about the following

Implementation of Bubble Sort
Implementation of Optimized Bubble Sort
Implementation of Insertion Sort
Several Java Example programs

Selection Sort in java


In computer science, selection sort is a sorting algorithm, Selection sort works from left to right typically. It finds the smallest element index and its swap with the current indexed element.

It is specifically an in-place comparison sort. It has O(n2) time complexity and worst than Insertion sort and better than Bubble sort.

We will discuss sorting in ascending and descending order for the given input array.

Selection Sort Simulation Example:

Selection sort animation. Red is current min. Yellow is sorted list. Blue is current item


Algorithm:

Outer Loop from index i 0 to length - 1
 minValueIndex = i;
  Inner loop from index j=i to length - 1
   if (A[minValueIndex] < A[j])
    minValueIndex = j;
   swap (A[minValueIndex], A[i])
  End Inner loop
End Outer loop

Ascending Order Example Program:

package com.adeepdrive.sorting;
public class SelectionSort {
 // Java - W3schools
 public static void main(String[] args) {
  int[] inputArray = { 5, 9, 3, 1, 7 };
  int length = inputArray.length;
  int minValueIndex;

  System.out.print("Before sorting input array: ");
  printInputArray(inputArray);
  // Outer Loop
  for (int i = 0; i < length; i++) {
   minValueIndex = i;
   // Inner Loop
   for (int j = i; j < length; j++) {

    if (inputArray[minValueIndex] > inputArray[j]) {
     minValueIndex = j;
    }
   }

   int temp = inputArray[minValueIndex];
   inputArray[minValueIndex] = inputArray[i];
   inputArray[i] = temp;
   System.out.print("\nIterate " + i + " : ");
   printInputArray(inputArray);
  }
  System.out.print("\nAfter sorting input array: ");
  printInputArray(inputArray);
 }

 public static void printInputArray(int[] values) {
  for (int value : values) {
   System.out.print(value + " ");
  }
 }
}


Output:

Before sorting input array: 5 9 3 1 7
Iterate 0 : 1 9 3 5 7
Iterate 1 : 1 3 9 5 7
Iterate 2 : 1 3 5 9 7
Iterate 3 : 1 3 5 7 9
Iterate 4 : 1 3 5 7 9
After sorting input array: 1 3 5 7 9

Descending Order Example Program:

In the above program just change the hi-lighted  line in Yellow background with the following line.
if (inputArray[minValueIndex] < inputArray[j]) {
Output:

Before sorting input array: 5 9 3 1 7
Iterate 0 : 9 5 3 1 7
Iterate 1 : 9 7 3 1 5
Iterate 2 : 9 7 5 1 3
Iterate 3 : 9 7 5 3 1
Iterate 4 : 9 7 5 3 1
After sorting input array: 9 7 5 3 1

Other Articles on Core Java


No comments:

Post a Comment

Please do not add any spam links in the comments section.