Skip to main content

Java Example of Selection Sort


Introduction

Selection sort is the simplest sorting algorithm in terms of implementation.
Let's consider we have a list of elements i.e. {3, 9, 0, 5, 4 }

a) Selection sort maintains two sublists, one sorted and initially empty and second unsorted sublist i.e.
[ {}, {3, 9 , 0, 5 ,4 }]

b) It searches for the minimum element (for ascending sort) OR for a maximum element( for descending sort) in the unsorted list in each step.

Step 1

[ {0 }, {9,3,5,4}]
Minimum element = 0 , swapped with 3

Step 2

Minimum element = 3 , swapped with 9
[{0,3) , {9,5,4} ]

Step 3

Minimum element = 4 , swapped with 9
[{0,3,4} , {5,9}]

Step 4

Minimum element = 5 , swapped with itself
[{0,3,4,5}, {9}]

Step 5

Minimum element = 9 , swapped with itself
[{0,3,4,5,9}, {}]

Worst Complexity: O(n*n)

Best Complexity   : O(n * n)


Imperative style implementation using Java 7

public class SelectionSortExample {

 private static int array[] = {3,9,0,5,4};

 public static void main(String[] args) {

  sortAscending();

  System.out.println("Ascending Sorted List");

  for(int value : array) {
   System.out.print(value + " ");
  }

  sortDescending();

  System.out.println("\nDescending Sorted List");

  for(int value : array) {
   System.out.print(value + " ");
  }
  }
 private static void sortAscending() {

  for(int outer=0; outer<array.length; outer++) {

   int minimumIndex = outer;
   for(int inner = outer+1; inner < array.length;inner++) {
    // array[minimumIndex] > array[inner]
    if(array[minimumIndex] > array[inner]) {
     minimumIndex = inner;
    }
   }

   int temp = array[outer]; 
   array[outer] = array[minimumIndex];
   array[minimumIndex] = temp;
  }
 }

 private static void sortDescending() {

  for(int outer=0; outer<array.length; outer++) {
   int minimumIndex = outer;
   for(int inner = outer+1; inner < array.length;inner++) {
    // array[minimumIndex] < array[inner
    if(array[minimumIndex] < array[inner]) {
     minimumIndex = inner;
    }
   }

   int temp = array[outer]; 
   array[outer] = array[minimumIndex];
   array[minimumIndex] = temp;
  }
 }
}

Declarative Style Implementation using Java 8 


import java.util.Arrays;
import java.util.stream.IntStream;
public class SelectionSortJava8Example {
private static int array[] = {0,5,2,6,3,1,-9};
static int minimumIndex = 0;
public static void main(String[] args) {
sortAscending();
System.out.println("Ascending Sorted List");
Arrays.stream(array).forEach(System.out::print);
sortDescending();
System.out.println();
System.out.println("Descending Sorted List");
Arrays.stream(array).forEach(System.out::print);
}
private static void sortAscending() {
IntStream.range(0, array.length).forEach(outer -> {
minimumIndex = outer;
IntStream.range(outer+1, array.length)
.forEach(inner -> {
// < is used for Ascedning sort
if(array[inner] < array[minimumIndex]) {
minimumIndex = inner;
}
});
//swap the elements
int temp = array[minimumIndex];
array[minimumIndex] = array[outer];
array[outer] = temp;
});
}
private static void sortDescending() {
IntStream.range(0, array.length).forEach(outer -> {
minimumIndex = outer;
IntStream.range(outer+1, array.length)
.forEach(inner -> {
// > is used for Descedning sort
if(array[inner] > array[minimumIndex]) {
minimumIndex = inner;
}
});
//swap the elements
int temp = array[minimumIndex];
array[minimumIndex] = array[outer];
array[outer] = temp;
});
}
}
Input   : 3,9, 0, 5 ,4
Output: 0 3 4 5 9 (Ascending)
Output: 9 5 4 3 0 (Descending)

Conclusion

In this tutorial, we learned how to implement Selection Sort using Java language. Please leave your comments in the comment box. Happy learning :)

Comments

Popular posts from this blog

Eclipse - Server Tomcat v8.5 Server at localhost failed to start.

When I try to launch the tomcat from Eclipse, I encountered the following error Server Tomcat v8.5 Server at localhost failed to start. Solution Step 1  Delete the .snap file located at the following location     eclipse workspace Path\ .metadata\.plugins\org.eclipse.core.resources Step 2 Delete the  tmp0  folder from the following path      eclipse workspace Path \.metadata\.plugins\org.eclipse.wst.server.core Step 3  Delete the server from servers list Step 4  Remove already added Tomcat Server      i)  Click on Define a new Server     ii)  Select Server Runtime Environments     iii) Select the Tomcat Server and remove it as follows Remove Selected Server Step 5 Make sure that correct version of Server is configured in Project Properties Step 6 Restart the Eclipse IDE.

Intellij : How to add @author comment to every new class

 Introduction In this tutorial, we will learn how to add @author comments to every new class that we create. We can achieve it using either of the following two solutions Solution 1:  Automatically add @author comments to every new class using Files and Code Templates Open File -> Settings -> Editor -> File and Code Templates -> Includes Click on Includes . Under File Header , enter the following comments text /**  * @author ${USER}  * @Date ${DATE}   */ Intellij - add @author comments Solution 2: Autocompletion of @author Open File  ->  Settings  ->  Editor  -> Live Templates Select Java and then click on + button In Abbreviation, enter @a In template text , enter the following comments           /**             * @author ${USER}             * @Date ${DATE}            */ In option , Expands with select SPACE Intellij - Autocompletion @author You can simply add the @author comments by typing @a and then click SPACE

hibernate-release-5.4.4.Final - Required Jars

Introduction Hibernate (Object Relational Mapping framework) is an implementation of Java Persistence API (JPA) specification.   Required Jars for Hibernate 5.4.4 Following Jars resided inside the required folder are the mandatory jars required for Hibernate 5.4.4 antlr-2.7.7.jar byte-buddy-1.9.11.jar classmate-1.3.4.jar dom4j-2.1.1.jar FastInfoset-1.2.15.jar hibernate-commons-annotations-5.1.0.Final.jar hibernate-core-5.4.4.Final.jar istack-commons-runtime-3.0.7.jar jandex-2.0.5.Final.jar javassist-3.24.0-GA.jar javax.activation-api-1.2.0.jar javax.persistence-api-2.2.jar jaxb-api-2.3.1.jar jaxb-runtime-2.3.1.jar jboss-logging-3.3.2.Final.jar jboss-transaction-api_1.2_spec-1.1.1.Final.jar stax-ex-1.8.jar txw2-2.3.1.jar Hibernate 5.4.4 release is compatible with  Java 8 or 11  JPA 2.2 References https://hibernate.org/orm/releases/5.4/