The Wayback Machine - https://web.archive.org/web/20240927175258/https://www.geeksforgeeks.org/java-program-for-selection-sort/
Open In App

Java Program for Selection Sort

Last Updated : 10 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the beginning.

Basic Principle of Selection Sort

The algorithm works by maintaining two subarrays in a given array:

  1. The subarray is already sorted.
  2. Remaining subarray which is unsorted.

In every iteration of the selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.

Java Selection Sort

Algorithm for Selection Sort

Implementation of Selection Sort in Java is mentioned below:

Step 1: Array arr with N size
Step 2: Initialise i=0 
Step 3: If(i<N-1) Check for any element arr[j] where j>i and arr[j]<arr[i] then Swap arr[i] and arr[j]
Step 4: i=i+1 and Goto Step 3
Step 5: Exit

Program to Implement Selection Sort Java

Java




// Java program for implementation
// of Selection Sort
  
// Driver Class
class SelectionSort {
    void sort(int arr[])
    {
        int n = arr.length;
  
        // One by one move boundary of unsorted subarray
        for (int i = 0; i < n - 1; i++) {
            // Find the minimum element in unsorted array
            int min_idx = i;
            for (int j = i + 1; j < n; j++) {
                if (arr[j] < arr[min_idx])
                    min_idx = j;
            }
  
            // Swap the found minimum element with the first
            // element
            int temp = arr[min_idx];
            arr[min_idx] = arr[i];
            arr[i] = temp;
        }
    }
  
    // Prints the array
    void printArray(int arr[])
    {
        int n = arr.length;
        for (int i = 0; i < n; ++i)
            System.out.print(arr[i] + " ");
        System.out.println();
    }
  
    // main function
    public static void main(String args[])
    {
        SelectionSort ob = new SelectionSort();
        int arr[] = { 64, 25, 12, 22, 11 };
  
        ob.sort(arr);
        System.out.println("Sorted array");
        ob.printArray(arr);
    }
}


Output

Sorted array
11 12 22 25 64 

Complexity of the Above Method

Time Complexity:  O(n2)
Auxiliary Space: O(1)

Please refer complete article on Selection Sort for more details!



Previous Article
Next Article

Similar Reads

Comparison among Bubble Sort, Selection Sort and Insertion Sort
Bubble Sort, Selection Sort, and Insertion Sort are simple sorting algorithms that are commonly used to sort small datasets or as building blocks for more complex sorting algorithms. Here's a comparison of the three algorithms: Bubble Sort:Time complexity: O(n^2) in the worst and average cases, O(n) in the best case (when the input array is already
15 min read
Program to sort an array of strings using Selection Sort
Given an array of strings, sort the array using Selection Sort. Examples: Input : paper true soap floppy flower Output : floppy, flower, paper, soap, true Prerequisite : Selection Sort. C/C++ Code // C++ program to implement selection sort for // array of strings. #include <bits/stdc++.h> #include <string.h> using namespace std; #define
7 min read
Selection Sort VS Bubble Sort
Not a valid contributionIn this, we will cover the comparison between Selection Sort VS Bubble Sort. The resources required by Selection Sort & Bubble Sort algorithms on the basis of Time and Space Complexity are as follows. Time Complexity - [Tex]O(n^2)[/Tex]Space Complexity - [Tex]O(1)[/Tex] Let’s dive deep into the working of these algorithm
13 min read
Is Selection Sort a Simple Sort?
Selection sort is a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted portion of the list and swapping it with the leftmost unsorted element. This process is repeated until the entire list is sorted. How Selection Sort Works?Selection sort works as follows: Start with the first unsorted element in the l
2 min read
Java Program For Recursive Selection Sort For Singly Linked List - Swapping Node Links
Given a singly linked list containing n nodes. The problem is to sort the list using the recursive selection sort technique. The approach should be such that it involves swapping node links instead of swapping node data. Examples: Input: 10 -> 12 -> 8 -> 4 -> 6 Output: 4 -> 6 -> 8 -> 10 -> 12 In Selection Sort, we first find
4 min read
8086 program for selection sort
Problem - Write an assembly language program in 8086 microprocessor to sort a given array of n numbers using Selection Sort. Assumptions - The number of elements in the array is stored at offset 500. The array starts from offset 501. Example - Algorithm - We first find the smallest number in the array. Swap the smallest number from the first elemen
3 min read
C++ program for Sorting Dates using Selection Sort
C/C++ Code // C++ program for sorting dates using selection sort #include&lt;bits/stdc++.h&gt; using namespace std; struct date { int day; int month; int year; }; int main() { struct date input[5]; for(int i=0; i&lt;5; i++) { cin&gt;&gt;input[i].day; cin&gt;&gt;input[i].month; cin&gt;&gt;input[i].year; } for (int
1 min read
Javascript Program For Recursive Selection Sort For Singly Linked List - Swapping Node Links
Given a singly linked list containing n nodes. The problem is to sort the list using the recursive selection sort technique. The approach should be such that it involves swapping node links instead of swapping node data. Examples: Input: 10 -> 12 -> 8 -> 4 -> 6Output: 4 -> 6 -> 8 -> 10 -> 12 In Selection Sort, we first find
4 min read
Selection Sort Visualizer in JavaScript
Selection sort is the simplest sorting algorithm that works by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the beginning. In order to know more about it. Please refer to Selection Sort An algorithm like Selection Sort can be easily understood by visualizing instead of long codes. In
5 min read
Time and Space complexity analysis of Selection Sort
The Selection sort algorithm has a time complexity of O(n^2) and a space complexity of O(1) since it does not require any additional memory space apart from a temporary variable used for swapping. Time Complexity Analysis of Selection Sort:Best-case: O(n2), best case occurs when the array is already sorted. (where n is the number of integers in an
2 min read
Recursive Selection Sort
The Selection Sort algorithm sorts maintain two parts. The first part that is already sortedThe second part is yet to be sorted. The algorithm works by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the end of the sorted part. arr[] = 64 25 12 22 11 // Find the minimum element in arr[0.
6 min read
Recursive selection sort for singly linked list | Swapping node links
Given a singly linked list containing n nodes. The problem is to sort the list using the recursive selection sort technique. The approach should be such that it involves swapping node links instead of swapping node data. Examples: Input : 10 -> 12 -> 8 -> 4 -> 6 Output : 4 -> 6 -> 8 -> 10 -> 12 In Selection Sort, we first fi
12 min read
A sorting algorithm that slightly improves on selection sort
As we know, selection sort algorithm takes the minimum on every pass on the array, and place it at its correct position.The idea is to take also the maximum on every pass and place it at its correct position. So in every pass, we keep track of both maximum and minimum and array becomes sorted from both ends. Examples: First example: 7 8 5 4 9 2 Inp
6 min read
Stable Selection Sort
A sorting algorithm is said to be stable if two objects with equal or same keys appear in the same order in sorted output as they appear in the input array to be sorted.Any comparison based sorting algorithm which is not stable by nature can be modified to be stable by changing the key comparison operation so that the comparison of two keys conside
6 min read
Top Interview Questions and Answers on Selection Sort
Selection sort is a simple and efficient sorting algorithm that works by repeatedly selecting the smallest (or largest) element from the unsorted portion of the list and moving it to the sorted portion of the list. In our article “Top Interview Questions and Answers on Selection Sort”, we present a collection of questions focused on Selection Sort.
5 min read
Sorting Algorithms Visualization | Selection Sort
The human brain can easily process visuals in spite of long codes to understand the algorithms. In this article, Selection Sort visualization has been implemented using graphics.h library. As we all know selection sort first finds the minimum element from the unsorted array and swaps it with the first element of the unsorted array in each pass. It
6 min read
Selection Sort Algorithm
Selection sort is a simple and efficient sorting algorithm that works by repeatedly selecting the smallest (or largest) element from the unsorted portion of the list and moving it to the sorted portion of the list.  The algorithm repeatedly selects the smallest (or largest) element from the unsorted portion of the list and swaps it with the first e
9 min read
Iterative selection sort for linked list
Given a linked list, the task is to sort the linked list in non-decreasing order by using selection sort.Examples: Input : Linked List = 5 ->3 ->4 ->1 ->2Output : 1 ->2 ->3 ->4 ->5 Input : Linked List = 5 ->4 ->3 ->2Output : 2 ->3 ->4 ->5 Table of Content [Expected Approach - 1] Swapping node Values - O(n^2
15+ min read
Java Program for Activity Selection Problem | Greedy Algo-1
You are given n activities with their start and finish times. Select the maximum number of activities that can be performed by a single person, assuming that a person can only work on a single activity at a time. Example: Example 1 : Consider the following 3 activities sorted by finish time. start[] = {10, 12, 20}; finish[] = {20, 25, 30}; A person
2 min read
Java Program for Odd-Even Sort / Brick Sort
This is basically a variation of bubble-sort. This algorithm is divided into two phases- Odd and Even Phase. The algorithm runs until the array elements are sorted and in each iteration two phases occurs- Odd and Even Phases. In the odd phase, we perform a bubble sort on odd indexed elements and in the even phase, we perform a bubble sort on even i
2 min read
Java Program to Sort Vector Using Collections.sort() Method
java.util.Collections.sort() method is present in java.util.Collections class. It is used to sort the elements present in the specified list of Collection in ascending order. Syntax: Public void sort(Vector object); Parameters: Instance of the vector as an argument Illustration: Collection.sort() method Let us suppose that our list contains {"Geeks
2 min read
Sort an array of pairs using Java Arrays.sort() with custom Comparator
Given an array of pairs of integers. The task is to sort the array with respect to the second element of the pair. Examples: Input: [(1, 2), (3, 5), (2, 6), (1, 7)]Output: [(1, 2), (3, 5), (2, 6), (1, 7)] Input: [(10, 20), (20, 30), (5, 6), (2, 5)]Output: [(2, 5), (5, 6), (10, 20), (20, 30)] Approach: Store the pairs in an array using a user-define
2 min read
Job Selection Problem - Loss Minimization Strategy | Set 2
We have discussed one loss minimization strategy before: Job Sequencing Problem – Loss Minimization. In this article, we will look at another strategy that applies to a slightly different problem.We are given a sequence of N goods of production numbered from 1 to N. Each good has a volume denoted by (Vi). The constraint is that once a good has been
9 min read
Activity selection problem with K persons
Given two arrays S[] and E[] of size N denoting starting and closing time of the shops and an integer value K denoting the number of people, the task is to find out the maximum number of shops they can visit in total if they visit each shop optimally based on the following conditions: A shop can be visited by only one personA person cannot visit an
10 min read
The Optimal Selection in an Array
There is an array given, the task is to select all of these integers in any order. For selecting every integer you get some points, and you need to maximize those points. For every integer you select, you get points equal to the value of the selected integer * the number of integers selected before the current integer, the task is to find the maxim
4 min read
Insertion sort to sort even and odd positioned elements in different orders
We are given an array. We need to sort the even positioned elements in the ascending order and the odd positioned elements in the descending order. We must apply insertion sort to sort them.Examples: Input : a[] = {7, 10, 11, 3, 6, 9, 2, 13, 0} Output : 11 3 7 9 6 10 2 13 0 Even positioned elements after sorting int ascending order : 3 9 10 13 Odd
7 min read
Quick Sort vs Merge Sort
Quick sort is an internal algorithm which is based on divide and conquer strategy. In this: The array of elements is divided into parts repeatedly until it is not possible to divide it further.It is also known as “partition exchange sort”.It uses a key element (pivot) for partitioning the elements.One left partition contains all those elements that
4 min read
Sort an Array which contain 1 to N values in O(N) using Cycle Sort
Prerequisite: Cycle SortGiven an array arr[] of elements from 1 to N, the task is to sort the given array in O(N) time.Examples: Input: arr[] = { 2, 1, 5, 4, 3} Output: 1 2 3 4 5 Explanation: Since arr[0] = 2 is not at correct position, then swap arr[0] with arr[arr[0] - 1] Now array becomes: arr[] = {1, 2, 5, 4, 3}Now arr[2] = 5 is not at correct
6 min read
Add elements in start to sort the array | Variation of Stalin Sort
Stalin sort (also 'dictator sort' and 'trump sort') is a nonsensical 'sorting' algorithm in which each element that is not in the correct order is simply eliminated from the list. This sorting algorithm is a less destructive variation of Stalin sort, that will actually sort the list: In this case, the elements that are not in order are moved to the
6 min read
sort() vs. partial_sort() vs. nth_element() + sort() in C++ STL
In this article, we will discuss the difference between sort(), partial_sort(), and nth_element()+sort(). Below is the illustration of the above functions: sort(): C++ STL provides a function sort() that sorts a list of element in O(N*log N) time. By default, sort() sorts an array in ascending order. Below is the program to illustrate sort(): // C+
4 min read
Article Tags :
Practice Tags :