×

Selection Sort in Java

Selection Sort in Java

Selection sort is also a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted portion of the input array, and placing it in the sorted portion of the array. Thus, selection sort maintains two subarrays, one is sorted and another one is not sorted. In every iteration, the size of the sorted subarray increases, and the size of the unsorted subarray decreases.

Algorithm and Pseudo Code

 selectionSort(arr, size)
 for( int i -> 0 to (size - 1) times )
  Assume that the first element encountered in each iteration, arr[i], as the current minimum element.
Store the index of the current minimum element, say minIndex
   for( int j -> i + 1 to size times)
    if arr[j] < arr[minIndex]
      update the minIndex as j
     end if
   end for
  swap the value present at the minIndex with first unsorted position, i.e, arr[i]
 end for
end selectionSort 

Selection Sort Java Program

The following Java program implements the selection sort algorithm.

FileName: SelectionSortExample.java

 public class SelectionSortExample
{
// method implementing the selection sort algorithm
static void selectionSort(int a[], int size)
{
    // outer loop iterates over elements of the array
    // starting from the first index and goes till the second last index
    for(int i = 0; i < size - 1; i++)
    {
        // assuming the first element of every iteration is
        // the minimum element and hence storing its index
        int minIndex = i;
        // iterating over elements starting from next to minIndex
        for(int j = i + 1; j < size; j++)
        {
            if(a[minIndex] > a[j])
            {
                // a[j] is smaller than the value
                // present at the minIndex.
                // Hence, updating the minIndex
                minIndex = j;
            }
        }
        // positioninig the element found
        // at the minIndex to its appropriate position
        int temp = a[minIndex];
        a[minIndex] = a[i];
        a[i] = temp;
    }
}
// main method
public static void main(String argvs[])
{
    // given input array
    int a[] = {67, 78, 34, 12, 30, 6, 9, 21};
    // calculating size of the array
    int size = a.length;
    System.out.println("The array before sorting is: ");
    for(int i = 0; i < size; i++)
    {
       System.out.print(a[i] + " ");
    }
    System.out.println("\n");
    // invoking method selectionSort()
    selectionSort(a, size);
    System.out.println("The array after sorting is: ");
    // displaying the sorted array
    for(int i = 0; i < size; i++)
    {
        System.out.print(a[i] + " ");
    }
}
} 

Output:

 The array before sorting is:
67 78 34 12 30 6 9 21
The array after sorting is:
6 9 12 21 30 34 67 78 

Explanation: In the above program, the first iteration of the outer loop finds the minimum element of the array, and the minimum element is placed at the first index, i.e., the 0th index, the second iteration of the outer loop finds the second minimum element of the array and puts the second minimum at the 1st index, the third iteration find the third minimum, places it on the 2nd index and so on for rest of the iteration. Thus, virtually dividing the array into the sorted and unsorted parts. The following diagram depicts the same.

Selection Sort in Java

It is the inner for-loop that does the searching of minimum elements. The outer loop tells the inner loop from where it should start the search of minimum element.

Analysis of the Selection Sort

If we observe, we find that selection sort is nothing but the reverse process of bubble sort. In bubble sort every, every iteration finds the maximum elements of the array and places those maximum elements at the rightmost side. In selection sort, every iteration finds the minimum elements of the array and places those minimum elements at the leftmost side. Thus, the behavior of the selection sort is almost similar to the selection sort.  The good thing about selection sort is it never makes more than n swaps to do the sorting, where n is the size of the array or list.

Time Complexity

Selection sort never cares about the arrangement of elements, i.e., even if a sorted array is provided as the input, the selection sort goes on to find the minimum element for the sorted array. Because of the nesting of two for loops, the time complexity of the selection sort is O(n^2), where n is the number of elements present in the list/ array. Since this sorting algorithm is independent of element arrangements, the best, average, or in the worst case, the time complexity remains the same, i.e., O(n^2).

Space Complexity

The selection sort does the in-place sorting. Therefore, the space complexity for the selection sort turns out to be O(1), i.e., constant space for sorting the input array or list.

Conclusion

Similar to bubble sort, this sorting algorithm should not be used for large lists or arrays because of the time complexity O(n^2). For a small list, one can go with the selection sort.


Related Topics

PriorityBlockingQueue Class in Java

What is the Queue? An abstract data structure like Stacks is a queue. A queue is open on both ends. Data is always pushed to one end, called enqueue, and removed...

4 minutes read.

Java String format() method

format() method returns a formatted String based on the given locale,specified format and arguments. Syntax: public static String format(String format , Object… args) Parameter: locale : It specifies locale value to be applied on...

2 minutes read.

Java Enumeration

In a computer language, enumerations express a set of named constants. For instance, the four suits in a deck of playing cards could be represented by the enumerators Club, Diamond,...

4 minutes read.

Check whether a Number is a Power of 4 or Not in Java

There are many ways to figure out if an integer is a power of 4. This section will go over a variety of techniques for figuring out whether or not...

11 minutes read.

Read the XLSX file in Java

Excel files contain cells; reading an excel file in Java differs from reading a word file. JDK doesn't have a direct API that can read or write Word or Excel...

3 minutes read.

Methods in Java

The Methods in Java are the collection of statements that are executed when the method is called. By using the methods, the complexity of writing the code decreases. The method consists...

4 minutes read.

Java Do While Loop

When we wish to test the exit condition at the end of the loop, we use a do-while loop. The do-while loop always executes its body at least once, because...

1 minute read.

How to Convert Integer to String in Java

How to Convert int to String in Java It is used when you want to convert an integer to String. You can convert int to String by using the following methods: Using...

3 minutes read.

Method and Block Synchronization in Java

The Synchronization is performed in multi-threading concept. The multi-threading is a concept of parallel running of a program for the execution. In the multi-threading concept, the threads are run by...

3 minutes read.

Java String Inbuilt functions

There are different types of inbuilt functions available in the Java String class, all of them are listed below. Char chat At (int index)It outputs the character indicated by the index....

5 minutes read.

Singleton class in Java

What is Singleton class in Java? Singleton means it is one. That means we can create only one instance or object of a class. For example, let us have a class...

3 minutes read.

Difference Between Access Specifiers and Modifiers in Java

Java employs access modifiers to restrict a class's data members, member functions, and constructor. Access modifiers are essential when creating Java program and applications. Access modifiers in Java include: defaultpublicprotectedprivate Default Access Modifiers Without...

4 minutes read.

Java Math.multiplyExact() method in Java

Java has an inbuilt math function called Math.multiplyExact() that returns the sum of the parameters. If the result exceeds an integer, an exception is thrown. There is no need to...

2 minutes read.

Sylvester Sequence in Java

A Sylvester Sequence is a series of numbers in which each term is the sum of the terms before it plus 1. The sequence's first two terms are 2 and...

3 minutes read.

How to make Java Projects

Ant and Maven are both offered by NetBeans for the development of Java applications. When using Ant, the IDE creates an Ant build script depending on the settings you select...

6 minutes read.

Java Char Keyword

The java char keyword is a data type which is defined as character data type.Char keyword belongs to a primitive data type where the data types are classified into primitive...

4 minutes read.

How to compare two dates in different format in Java?

We need to compare two dates frequently when coding. Real-world examples include sorting a list of persons by age or keeping track of students' attendance. To compare two dates, we...

7 minutes read.

Generic queue in Java

Before understanding how to implement a generic queue in java, one must know about generics and queue in java. Generics in Java Generics are parameterized types. The goal is to enable type...

6 minutes read.

How to check data type in Java

In this section, we will learn about the methodology to verify the data type in Java. There are mainly two methods in java called as getClass() and getName(). They are...

3 minutes read.

ArrayList Program in Java

ArrayList Program in Java: In Java, ArrayList is a class that belongs to java.util package. It is the dynamic list that grows or shrinks at run-time as per the requirements....

4 minutes read.