×

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

Java String equals() method

equals() method compares two string based on the their content. Syntax public boolean equals(Objects anObject) parameter anObject: Object to be compared with the current String. Returns It returns true when the current String is equivalent to...

1 minute read.

Java Program to find the smallest element in a tree

The variable min is used to store the data of the root, which is initially defined. The smallest node in the left subtree is then located by moving through the...

3 minutes read.

Java HashSet

HashSet implements the set interface. It uses the hash table to make the collection to store different data types. The hash set is the unordered collection of different data types....

6 minutes read.

Difference Between BufferedReader and FileReader

BufferedReader: To read data from a specified character stream, two classes are used: buffered readers and file readers. Both of them have advantages and disadvantages. Although how they operate is the...

6 minutes read.

Java Delete File

There are two techniques to erase a record in Java: Utilizing File.delete() technique.Utilizing File.deleteOnExit() technique. Using File.delete() technique: In Java, we can erase a document by utilizing the File.delete() technique for File class....

2 minutes read.

Class memory in Java

Anything specifically defined in the Java code is stored either inside the heap or the stack, which is particularly significant. Stack and heap are the two kinds of memory available...

6 minutes read.

Java 9 Tutorial

The Java 9 is most popular release of java programming to make it platform modular. It is used to improve JDK and java implementation security. It provides JAVA SE and...

3 minutes read.

How to Split the String in Java with Delimiter

In Java, splitting strings is a significant and typically used activity while coding. Java gives different ways of dividing the String. The most widely recognized way is to use the...

3 minutes read.

Snake and Ladder Problem in Java

Find the smallest number of dice throws necessary to reach the destination or last cell from the source or first cell on a snake and ladder board. Essentially, the player...

6 minutes read.

Dutch National Flag Problem in Java

Dutch National Flag (DNF) is a programming issue that Edsger Dijkstra put up. The white, red, and blue hues make up the Dutch flag. The goal is to haphazardly set...

6 minutes read.

Array Slicing in Java

Array slicing is a method in Java for obtaining a subarray of a specified array. Assume a[] is an array. It contains eight items indexed from a[0] to a[7].a[] =...

3 minutes read.

Java Tutorial

What is Java? Java is an object-oriented, robust, secured and platform-independent programming language. With the help of Java Programming, we can develop console, window, web, enterprise and mobile applications. Java language was...

22 minutes read.

Sublime Number in Java

In this tutorial, we will understand what is meant by sublime number in java. From the point of the coding interview, it is one of the important topics. We will we will...

4 minutes read.

Char and String differences in Java

Characters in Java Character (char) belongs to the characters group, which represents symbols in a character set, such as alphabets and numerals. A Java char has 16 bits in length and has a range...

5 minutes read.

XNOR operator in Java

The opposite of the binary equivalent of XOR is given by XNOR. Truth table: XYXNOR001010100111 If the bits are the same, it returns 1, else it returns 0. Examples:  Input: 10 20 Output : 1 A Binary...

3 minutes read.

Exception Handling Program in Java

Exception Handling Program in Java Exception means something that is abnormal. In Java, an exception is treated as a problem that disrupts the normal flow of the program. An exception leads...

7 minutes read.

How to Convert String to Object in Java

How to Convert String to Object in Java The Object is the super class of all classes. So you can assign a string to Object directly. There are two methods to...

3 minutes read.

String isnullorempty in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java Math with Methods and Examples

Java Math class contains various methods for performing math operations like min(), max(), avg() and various trigonometric functions like sin(), cos(), tan() etc. Methods: The java.lang.Math class contains various methods for performing...

5 minutes read.

How to Convert boolean to String in Java

How to Convert boolean to String in Java There are two methods to convert boolean to String. Using valueOf(boolean) method Using toString(boolean) method For both the above methods, if the passes Boolean...

2 minutes read.