Table of Contents
How Selection Sort Works in Java
Algorithm
Examples to Implement Selection Sort in Java
Java Program to Sort the Elements in an Array using Selection Sort
Java Program to Sort the Elements using Selection Sort
Performance of Selection Sort
Conclusion
Home Java javaTutorial Selection Sort In Java

Selection Sort In Java

Aug 30, 2024 pm 03:30 PM
java

Selection Sort in Java is a sorting method that continually finds the smallest element in the unsorted part and keeps it in the beginning (for sorting in ascending order). The process will be repeated until the input array is sorted. Also, in Selection Sort, we will be dividing the input array into two subarrays where one array is used for sorted elements and the other array is for unsorted elements. In the beginning, there won’t be any elements in the sorted subarray. Let us see the working of the selection sort in detail in the following section.

How Selection Sort Works in Java

Selection sort works in a simple manner where it keeps two subarrays from the input array. They are:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

  • Sorted subarray to keep the sorted elements
  • Unsorted subarray to keep the unsorted elements.

Algorithm

Following is the algorithm that is used for Selection sort

  1. Set the minimum (MIN) pointer to location 0.
  2. Find the smallest element from the list of elements in the array
  • Swap the minimum element with the location 0
  1. Move the MIN pointer to the next position
  2. Repeat the process until the input array is sorted.

Let us understand the selection sort with an example. Following is the input array that has to be sorted. The elements in Bold Blue color will be as part of the sorted array.

Selection Sort In Java

Step 1: Set the MIN pointer to the first location. So, the MIN pointer points to 15.

Selection Sort In Java

Smallest: = 15

Step 2: Find the smallest element by comparing it with the rest of the elements. Comparing 15 and 21, 15 is the smallest. So, the smallest won’t change in this case.

Selection Sort In Java

Smallest: = 15

Comparing 15 and 6, 6 is the smallest.

Selection Sort In Java

Smallest: = 6

Comparing 6 and 3, 3 is the smallest.

Selection Sort In Java

Smallest: = 3

3 will be smaller in this case also, as 19 is greater than 3.

Selection Sort In Java

Smallest: = 3

Selection Sort In Java

Smallest: = 3

Finally, in this iteration, 3 is found to be the smallest.

Step 3: Swap the smallest element with the element in location 0.

Selection Sort In Java

Step 4: Increment the MIN pointer to the next position.

Selection Sort In Java

Step 5: Find the next smallest element by comparing it with the rest of the elements.

Selection Sort In Java

Smallest: = 21

Selection Sort In Java

Smallest: = 6

Selection Sort In Java

Smallest: = 6

Selection Sort In Java

Smallest: = 6

Selection Sort In Java

Smallest: = 6

Step 6: Swap the smallest element with the element in location 1.

Selection Sort In Java

Repeat the process until a sorted array is formed, as shown below.

Selection Sort In Java

Examples to Implement Selection Sort in Java

As already mentioned above, selection sort is based on finding the minimum and swapping. Now, let us see how to implement the selection sort using Java.

Java Program to Sort the Elements in an Array using Selection Sort

Code:

import java.util.*;
public class SelSortExample {
//Method that implements Selectionsort
public static void selsort(int[] arr)
{
int n=arr.length; //length of the array
for(int i=0;i<n-1;i++)
{
int MIN=i; //set the first position as minimum
System.out.println("Sorting based on Number "+(i+1));
//Find the smallest element by comparing with the element in MIN position
for(int j=i+1;j<n;j++)
{
System.out.println("Comparing "+ arr[MIN] + " and " + arr[j]);
if(arr[j]<arr[MIN])
{
System.out.println(arr[MIN] + " is greater than " + arr[j] );
MIN=j;
}
}
//Swap the smallest element with element in MIN position
int temp=arr[i];
arr[i]=arr[MIN];
arr[MIN]=temp;
}
}
public static void main(String[] args) {
int[] arr= {15,21,6,3,19,20}; // input array
System.out.println("Elements in the array before Sorting: "+ Arrays.<em>toString</em>(arr));
<em>selsort</em>(arr);//calling the selection sort method
System.out.println("Elements in the array after Sorting: "+Arrays.<em>toString</em>(arr));
}
}
Copy after login

Sample Output:

Selection Sort In Java

In the above program, we have two methods-main methods and the sell sort method. The main method calls the sell sort method passing the input array as the argument. The minimum element will be identified and swapped with the element pointed by MIN.

The selection sort can also be used where the input array is not defined in code. Let us see how it works using the below program.

Java Program to Sort the Elements using Selection Sort

Code:

import java.util.*;
public class SelectionSortExample
{
public static void main(String args[])
{
int n, i, j, tempvar;
Scanner <u>sc</u> = new Scanner(System.in); //To take the input from user
System.out.print("Enter the size of array : \n");
n = sc.nextInt();
int array[] = new int[n]; //<u>initialising</u> the array
System.out.print("Enter the elements that need to be inserted in the array : \n");
//inserting the elements to the array
for(i=0; i<n; i++)
{
array[i] = sc.nextInt();
}
System.out.print("array before Sorting: \n"+ Arrays.toString(array));
System.out.print("\nSorting begins here..\n");
for(i=0; i<n; i++)
{
for(j=i+1; j<n; j++)
{
if(array[i] > array[j])
{
tempvar = array[i];
array[i] = array[j];
array[j] = tempvar;
}
}
}
System.out.print("Array after Sorting is :\n");
for(i=0; i<n; i++)
{
System.out.print(array[i]+ " ");
}
}
}
Copy after login

Sample Output:

Selection Sort In Java

Here, the input elements given by the user will be compared with the temporary variable and swapped. The process will be repeated until a sorted array is formed.

Performance of Selection Sort

This sorting technique is used for its simplicity and certain other performance advantages over other more sorting techniques.

Selection Sort In Java

Conclusion

The selection sort does not work efficiently on large lists as it consumes more time for comparison. Selection sort is a method in which an input array will be divided into two subarrays in order to keep them sorted and unsorted elements. The minimum element in the array will be swapped with the element in the first position, and the process continues until a sorted array is formed.

The above is the detailed content of Selection Sort In Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

H5: Tools, Frameworks, and Best Practices H5: Tools, Frameworks, and Best Practices Apr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

See all articles