×

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

Thread Safety and How to Achieve it in Java

Before diving into the topic, let’s just recap the concept of Multithreading provided by Java where we can create and execute multiple threads of the same object. When these multiple...

5 minutes read.

Java Set to List

In this article, you will be acknowledged about how the process of conversion from Set or HashSet to LinkedList happens and what are the possible ways involved in conversion process. First...

4 minutes read.

HashMap Vs HashTable

HashMap HashMap is the basic implementation of the map interface in Java. HashMap stores the data in key and value pairs. Keys are used to access the value of the element. It...

5 minutes read.

Java Math log() Method

The log() method of Math class returns the natural logarithmic value for the specified double argument. Syntax: public static double log(double a) Parameters: The parameter ‘a’ represents the value. Return Value: The log() method returns the...

1 minute read.

Java Integer doubleValue() method

The doubleValue() method of Integer class returns a double value for this Integer after a widening primitive conversion. Syntax public double doubleValue() Parameters NA Specified by This method is specified by doubleValue in class Number Return Value This...

1 minute read.

Add numbers represented by Linked Lists in Java

For calculating the sum of the two numbers that are represented by a linked list, and then store the result in a new linked list. A linked list's head node...

7 minutes read.

Diffie Hellman Algorithm in Java

In this section, you will be acknowledged about Diffie Hellman algorithm clearly step wise along with an example and also an example program. Diffie Hellman Algorithm One of the most significant algorithms...

3 minutes read.

Replace character in string Java

Characters in Java In the package of Java language, there is a container class called Character. A single field of type char is contained in a Character object. For manipulating characters,...

4 minutes read.

Swastika Pattern in Java

This part teaches us how to create the Swastika Pattern in Java utilizing user-defined columns and rows as well as stars or other special characters.A Java pattern application that is...

2 minutes read.

Why are generics used in Java

Java has a feature called generics that allows you to make a class, interface, and function accepting any (reference) type as a parameter. In other words, it is the idea...

4 minutes read.

DatabaseMetaData in Java

The Data about another data is called Meta data. The DatabaseMetaData interface has the meta data of the database present in the system. It consists of database product name, total...

2 minutes read.

Java Throw and Throws Keyword

Exceptions in Java enable us to construct high-quality programs where faults are checked at compile time rather than run time and where we may define unique exceptions that make code...

6 minutes read.

What is Core Java?

The fundamental Java, which includes the fundamental idea of the Java programming language, is referred to as "Core Java." The definition of "Core" is the core idea of something. Core...

3 minutes read.

Compare time in java

Introduction: This article discusses how to compare time in java. Maximum of the time we need to examine the date and datetime items. Date comparisons are vital if you want to...

3 minutes read.

How to Reduce Time Complexity in Java

What is time complexity?  The time complexity in java is given as the amount of time a program requires to run or execute it Calculating the time complexity of the program The time...

4 minutes read.

How to Convert Decimal to Octal in Java

How to Convert Decimal to Octal in Java There are two methods to convert Decimal to Octal: Using toOcatlString() method Using user-defined logic Using Integer.toOctalString() method The toOctalString() is astaticmethod of the Integer...

2 minutes read.

Count of Range Sum Problem in Java

In this article, we will discuss the basic approach or native approach used to count range sum problem in java. To solve this problem, we will check for numbers if they...

6 minutes read.

Java LinkedList

LinkedList Java The Java LinkedList is used to store the elements by using a doubly linked list. It contains the duplicate items, also maintains the order of the insertion, the class...

5 minutes read.

Java protected vs private

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

Java Macros

Macros are additions to the JDK 7 compiler in Java. Compile time macros are added and supported. Macros are Java classes that are instantiated and executed during the compilation process....

2 minutes read.