top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Selection Sort Java

Introduction 

Selection sort in Java is a simple yet efficient sorting algorithm widely used in Java programming. It provides a straightforward approach to sorting elements in an array or a collection in ascending or descending order. 

Selection sort offers a practical and intuitive solution for arranging data in a desired sequence. By understanding the principles behind selection sort and its implementation in Java, you can enhance your programming skills and effectively organize your data. 

Overview

In this tutorial, we will explore the concept of selection sort in Java, including the selection sort Java ArrayList technique.

Selection Sort Algorithm  

The selection sort algorithm is a straightforward sorting method that involves finding the smallest (or largest) element from a section of an array that is yet to be sorted, and exchanging it with the element at the start of the unsorted section, thereby gradually sorting the array.

Here is the step-by-step process of the selection sort algorithm:

  • Start with an unsorted array of elements.

  • Iterate through the array from the first element to the second-to-last element.

  • Assume the current element as the minimum (or maximum) valu

  • Compare the current element with the remaining elements in the unsorted portion.

  • If a smaller (or larger) element is found, update the minimum (or maximum) value.

  • After completing the iteration, swap the minimum (or maximum) value with the first unsorted element.

  • Move the boundary of the sorted portion one position to the right.

  • Repeat steps 2-7 until the entire array is sorted.

Selection Sort in Java – Data Structure and Algorithm

Selection sort in Java belongs to the category of comparison-based sorting algorithms and is characterized by its simplicity and ease of implementation. Understanding the inner workings of selection sort is essential for any programmer or computer scientist studying data structures and algorithms.

Here is the step-by-step process of the selection sort algorithm:

  • Set the minimum index variable to the first element's index.

  • Iterate through the unsorted part of the array from the second element to the last.

  • In each iteration, find the minimum element in the unsorted part by comparing each element with the current minimum.

  • If a smaller element is found, update the minimum index.

  • Swap the minimum element with the first element of the unsorted part.

  • Move the boundary of the sorted subarray one position to the right.

  • Repeat steps 2-5 until the entire array is sorted.

Selection sort has a time complexity of O(n^2), where n is the number of elements in the array. It is an in-place sorting algorithm since it requires no additional memory apart from the input array.

How Does Selection Sort in Java Algorithm Work? 

Selection sort is a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted part of the array and swapping it with the element at the beginning of the unsorted part. The algorithm maintains two subarrays: the sorted subarray and the unsorted subarray. The sorted subarray is initially empty, and the unsorted subarray contains all the elements.

Complexity Analysis of Selection Sort in Java

The complexity analysis of an algorithm helps us understand how its performance scales with the input size. Let's analyze the complexity of the selection sort algorithm in Java.

Selection sort is a simple comparison-based sorting algorithm. It works by dividing the input array into two parts: the sorted part at the beginning and the unsorted part at the end. In each iteration, the algorithm finds the minimum (or maximum) element from the unsorted part and swaps it with the first element of the unsorted part. This process continues until the entire array is sorted.

Here's the step-by-step breakdown of the selection sort algorithm:

  • Find the minimum element in the unsorted part of the array.

  • Swap the minimum element with the first element in the unsorted part.

  • Move the boundary of the sorted part one position to the right.

Now let's analyze the complexity of selection sort:

Time Complexity

  • Best-case time complexity: O(n^2)

  • Average-case time complexity: O(n^2)

  • Worst-case time complexity: O(n^2)

In the best-case scenario, the input array is already sorted. However, selection sort does not take advantage of this fact and still performs the same number of comparisons and swaps as in the average and worst cases. Therefore, the best-case time complexity is still O(n^2).

In the average and worst cases, the outer loop iterates n times, where n is the number of elements in the array. For each iteration, the inner loop performs n - i comparisons, where i is the current iteration index. This results in a total of (n-1) + (n-2) + ... + 1 = (n * (n-1)) / 2 comparisons and swaps.

Thus, the time complexity of the selection sort is O(n^2) in all cases.

Space Complexity

Selection sort is an in-place sorting algorithm, meaning it does not require additional memory proportional to the input size. Therefore, the space complexity of the selection sort is O(1) (constant space).

Java Program for Selection Sort in Ascending Order Example

import java.util.Arrays;

public class upGradTutorials {
    public static void selectionSort(int[] arr) {
        int n = arr.length;

        for (int i = 0; i < n - 1; i++) {
            int minIndex = i;

            for (int j = i + 1; j < n; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }

            // Swap the minimum element with the first element of the unsorted part
            int temp = arr[minIndex];
            arr[minIndex] = arr[i];
            arr[i] = temp;
        }
    }

    public static void main(String[] args) {
        int[] arr = {64, 25, 12, 22, 11};
        System.out.println("Before sorting: " + Arrays.toString(arr));

        selectionSort(arr);

        System.out.println("After sorting: " + Arrays.toString(arr));
    }
}

In the selectionSort method, the input array arr is passed as a parameter. The algorithm initializes a variable n to store the array's length.

The outer loop iterates from the first element to the second-to-last element of the array. At each iteration, it assumes the current element is the minimum value and assigns its index to the variable minIndex. The inner loop then starts from the next element after the current element and compares each subsequent element with the assumed minimum element. If a smaller element is found, the index of that element is updated in minIndex.

After completing the inner loop, the minimum element in the unsorted part of the array is found. It is then swapped with the first element of the unsorted part by using a temporary variable temp. This process continues until the entire array is sorted, with each iteration finding the minimum element and moving it to the correct position in the sorted portion of the array.

In the main method, an array arr is initialized with some values. The array is then printed before sorting using Arrays.toString(arr). The selectionSort method is called to sort the array. After sorting, the sorted array is printed using Arrays.toString(arr) to display the elements in ascending order.

Selection Sort in Java (Alternative Method)

import java.util.Arrays;

public class upGradTutorials {
    public static void selectionSort(int[] arr) {
        int n = arr.length;

        for (int i = 0; i < n - 1; i++) {
            int minIndex = i;

            for (int j = i + 1; j < n; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }


            // Swap the elements using XOR operation
            arr[i] = arr[i] ^ arr[minIndex];
            arr[minIndex] = arr[i] ^ arr[minIndex];
            arr[i] = arr[i] ^ arr[minIndex];
        }
    }

    public static void main(String[] args) {
        int[] arr = {64, 25, 12, 22, 11};
        System.out.println("Before sorting: " + Arrays.toString(arr));

        selectionSort(arr);

        System.out.println("After sorting: " + Arrays.toString(arr));
    }
}

This implementation follows the same selection sort algorithm, with slight variation in the element swapping process. Instead of using a temporary variable, it uses the XOR operation to swap the elements

In the selectionSort method, the array is iterated using two nested loops. The outer loop determines the current minimum element's index, and the inner loop compares the remaining elements to find the smallest element.

Once the minimum element is found, the XOR operation swaps the elements without requiring a temporary variable. This is achieved by performing XOR operations on the elements' values. This bitwise operation allows the elements to be swapped in place.

The main method initializes an array with some values, and the selectionSort method is called to sort the array in ascending order. Finally, the sorted array is printed before and after the sorting process.

Advantages of Selection Sort Algorithm

The selection sort algorithm, although simple, offers a few advantages:

  • Simplicity: Selection sort has a straightforward implementation that is easy to understand and implement. It does not involve complex logic or intricate data structures, making it accessible to programmers of all skill levels.

  • In-Place Sorting: Selection sort is advantageous in terms of memory efficiency as it works directly on the array without additional data structures, swapping elements within the array to achieve sorting.

  • Minimal Swapping: Selection sort minimizes the number of swaps required during the sorting process. It only performs swaps when necessary, specifically when finding the minimum (or maximum) element to place it in its correct position.

  • Stable Sorting: The selection sort is recognized as a stable sorting algorithm, ensuring that the relative order of elements with equal values is preserved. When two elements have the same value, their initial order will remain unchanged after sorting.

  • Adaptive Nature: Selection sort performs well on small lists or arrays with a small number of elements. Its performance is not affected by the initial order of the elements, making it suitable for situations where the input data is partially sorted or nearly sorted.

Disadvantages of the Selection Sort Algorithm

While selection sort has its advantages, it also has several disadvantages:

  • Quadratic Time Complexity: The main drawback of selection sort is its time complexity. It requires nested loops to find the minimum (or maximum) element and perform swaps, resulting in a worst-case and average-case time complexity of O(n^2). 

As the number of elements increases, the sorting time grows quadratically, making it inefficient for large datasets.

  • Lack of Efficiency for Large Arrays: Selection sort is unsuitable for sorting large arrays or datasets. Due to its quadratic time complexity, it becomes noticeably slower as the number of elements increases. 

Other sorting algorithms like Quicksort or Mergesort offer better performance for large datasets with faster time complexities.

  • Unstable Sort: The selection sort is considered an unstable sorting algorithm, which implies that it has the potential to alter the relative order of elements with identical values. When two elements have the same value, their original order may not be maintained after sorting.

This can be a disadvantage when maintaining the order of equal elements is important.

  • Redundant Comparisons: During each iteration, selection sort compares all the remaining elements in the unsorted portion to find the minimum (or maximum) value. This includes comparing elements that have already been sorted. 

These redundant comparisons result in unnecessary computational work and inefficiency in the algorithm.

  • Lack of Adaptive Behavior: Selection sort does not take advantage of any pre-existing order in the input data. Regardless of whether the data is partially sorted or in random order, the algorithm performs the same number of comparisons and swaps. 

This lack of adaptiveness can make it less efficient than other algorithms that exploit the initial order of the data.

Conclusion 

Selection sort is a straightforward sorting algorithm that can be implemented in Java. It operates by iteratively finding the smallest (or largest) element and placing it in its correct position. Selection sort is not the most efficient choice for sorting large datasets, but it can serve as a useful learning tool for understanding sorting algorithms and principles. 

Nonetheless, it is a foundational concept in sorting algorithms and provides valuable insights into algorithmic thinking and problem-solving. 

FAQs

1. What is insertion sort in Java?

Insertion sort in Java is a sorting algorithm that iteratively builds a sorted portion of an array by inserting elements into their correct positions.

2, What is bubble sort in Java?

Bubble sort in Java is a straightforward sorting algorithm that compares neighboring elements and swaps them if they are in the incorrect order, progressively moving larger elements toward the end of the array.

3. What is the selection sort program in C?

The selection sort program in C is a C language implementation of the selection sort algorithm, which sorts an array by repeatedly finding the minimum element and placing it in its correct position.

Leave a Reply

Your email address will not be published. Required fields are marked *