Tutorial Playlist
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.
In this tutorial, we will explore the concept of selection sort in Java, including the selection sort Java ArrayList technique.
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:
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:
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.
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.
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:
Now let's analyze the complexity of selection sort:
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.
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).
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.
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.
The selection sort algorithm, although simple, offers a few advantages:
While selection sort has its advantages, it also has several disadvantages:
As the number of elements increases, the sorting time grows quadratically, making it inefficient for large datasets.
Other sorting algorithms like Quicksort or Mergesort offer better performance for large datasets with faster time complexities.
This can be a disadvantage when maintaining the order of equal elements is important.
These redundant comparisons result in unnecessary computational work and inefficiency in the algorithm.
This lack of adaptiveness can make it less efficient than other algorithms that exploit the initial order of the data.
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.
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.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...