{"id":4270,"date":"2024-06-14T16:05:40","date_gmt":"2024-06-14T16:05:40","guid":{"rendered":"https:\/\/msgprogramator.sk\/?p=4270"},"modified":"2026-02-17T11:24:28","modified_gmt":"2026-02-17T11:24:28","slug":"selection-sort","status":"publish","type":"post","link":"https:\/\/msgprogramator.sk\/en\/selection-sort\/","title":{"rendered":"Selection sort algorithm Java"},"content":{"rendered":"<p>Selection sort algorithms are used to reorder the elements of an array or list in ascending or descending numerical or lexicographic order. Sorting is very important for the optimal performance of other algorithms that require sorted input data.<\/p>\n<p>There are a number of different sorting algorithms. The selection of an appropriate algorithm depends on factors such as the size and characteristics of the input data, available memory, and time and space requirements.<\/p>\n<p>To make your choice easier, in our series we will introduce the most well-known data sorting algorithms, explain their principles, advantages and disadvantages, and program them in Java.<\/p>\n<p>So far, we have discussed the following sorting algorithms:<\/p>\n<ul>\n<li><a href=\"https:\/\/msgprogramator.sk\/en\/sorting-algorithms\/\" target=\"_blank\" rel=\"noopener\">Sorting algorithms<\/a>: Introduction to data sorting<\/li>\n<li><a href=\"https:\/\/msgprogramator.sk\/en\/bubble-sort\/\" target=\"_blank\" rel=\"noopener\">Bubble sort<\/a><\/li>\n<li><a href=\"https:\/\/msgprogramator.sk\/en\/comb-sort\/\" target=\"_blank\" rel=\"noopener\">Comb sort<\/a><\/li>\n<li><a href=\"https:\/\/msgprogramator.sk\/en\/big-o-notation\/\" target=\"_blank\" rel=\"noopener\">Big O notation<\/a>: analysis of algorithms&#8217; time and space complexity<\/li>\n<\/ul>\n<p>Today we are going to look at <strong>selection sort<\/strong>.<\/p>\n<h2>Selection sort algorithm<\/h2>\n<p>Selection sort is a simple data sorting algorithm that divides the input field into two parts: sorted and unsorted. It then repeatedly selects the smallest (largest) element from the unsorted part and moves it to the sorted part. The algorithm is very inefficient for large numbers of elements in the input, but it is often used in situations where there are relatively few elements in the input, usually in combination with other sorting algorithms.<\/p>\n<h2>How selection sort works<\/h2>\n<p>Suppose we want to sort the input vector from smallest to largest element. For reverse sorting, the whole logic of the algorithm is inverted. The sorted part of the array is always empty at the start of the algorithm.<\/p>\n<ol>\n<li>At the beginning of the algorithm, we assume that the first element (of the unsorted part) is the minimum (i.e., the smallest).<\/li>\n<li>We compare this element with the remaining elements in the unsorted part of the array and look for the true minimum.<\/li>\n<li>If we find a minor element in the unsorted part, we replace the elements.<\/li>\n<li>The replaced element becomes part of the sorted dataset, its index is increased by 1 and the unsorted part is decreased.<\/li>\n<li>Repeat steps 1 to 4 until the entire field is sorted.<\/li>\n<\/ol>\n<p>We will later show a practical selection sort example in Java code.<\/p>\n<h2>Selection sort advantages<\/h2>\n<ul>\n<li>Easy to understand and implement<\/li>\n<li>Works well for small lists of data<\/li>\n<\/ul>\n<h2>Selection sort disadvantages<\/h2>\n<ul>\n<li>The time complexity is O(n\u00b2), making it a slow algorithm for a large dataset<\/li>\n<li>Not stable<\/li>\n<\/ul>\n<h2>Selection sort time complexity<\/h2>\n<table style=\"height: 96px\" width=\"496\">\n<thead>\n<tr style=\"height: 24px\">\n<th style=\"height: 48px;width: 85.5875px\" rowspan=\"2\"><strong>Algorithm<\/strong><\/th>\n<th style=\"height: 48px;width: 70px\" rowspan=\"2\"><strong>Method<\/strong><\/th>\n<th style=\"height: 24px;width: 182.15px\" colspan=\"3\"><strong>Time Complexity<\/strong><\/th>\n<th style=\"height: 48px;width: 72.2px\" rowspan=\"2\"><strong>Memory<\/strong><\/th>\n<th style=\"height: 48px;width: 56.8625px\" rowspan=\"2\"><strong>Stable<\/strong><\/th>\n<\/tr>\n<tr style=\"height: 24px\">\n<th style=\"height: 24px;width: 56.0875px\"><strong>worst<\/strong><\/th>\n<th style=\"height: 24px;width: 63.9875px\"><strong>average<\/strong><\/th>\n<th style=\"height: 24px;width: 51.675px\"><strong>best<\/strong><\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr style=\"height: 48px\">\n<td style=\"height: 48px;width: 85.5875px\">Selection sort<\/td>\n<td style=\"height: 48px;width: 70px\">Selection<\/td>\n<td style=\"height: 48px;width: 56.0875px\">O(n\u00b2)<\/td>\n<td style=\"height: 48px;width: 63.9875px\">O(n\u00b2)<\/td>\n<td style=\"height: 48px;width: 51.675px\">O(n\u00b2)<\/td>\n<td style=\"height: 48px;width: 72.2px\">O(1)<\/td>\n<td style=\"height: 48px;width: 56.8625px\">No<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h2>Selection sort animation, visualization, gif<\/h2>\n<p>The visualization of the Selection sort algorithm looks like this:<\/p>\n<figure id=\"attachment_3607\" aria-describedby=\"caption-attachment-3607\" style=\"width: 100px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-3606 size-full\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/06\/Selection-Sort-Animation.gif\" alt=\"selection sort animation\" width=\"100\" height=\"371\" \/><figcaption id=\"caption-attachment-3607\" class=\"wp-caption-text\">en:Joestape89, CC BY-SA 4.0, via Wikimedia Commons<\/figcaption><\/figure>\n<p style=\"text-align: center\"><em><span class=\"wp-caption-text\">Source: commons.wikimedia.org\/wiki\/Category:Animations_of_sort_algorithms<\/span><\/em><\/p>\n<p>To see how the algorithm is animated, go to <a href=\"https:\/\/www.toptal.com\/developers\/sorting-algorithms\" target=\"_blank\" rel=\"nofollow noopener\">Toptal.<\/a> There are 8 types of algorithms. You can also play the animation backwards.<\/p>\n<p>On <a href=\"https:\/\/www.hackerearth.com\/practice\/algorithms\/sorting\/selection-sort\/visualize\/\" target=\"_blank\" rel=\"nofollow noopener\"> this page<\/a> you can go through the steps of the algorithm to check the time taken by the algorithm.<\/p>\n<h2>Selection sort Java implementation<\/h2>\n<p>learned the principles of the algorithm, we can now program it in Java.<\/p>\n<p><strong><u>SelectionSort.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package sorting;\n\npublic class SelectionSort {\n    private boolean change;\n    private int temp;\n\n    public void sort(int data[])\n    {\n        for (int i = 0; i &lt; data.length - 1; i++) {\n            System.out.println(i + 1 + &quot;. iteration&quot;);\n            \/\/ Find the index of the minimum in unsorted part of array\n            int minIndex = i;\n            for (int j = i + 1; j &lt; data.length; j++) {\n                if (data[j] &lt; data[minIndex])\n                    minIndex = j;\n            }\n\n            \/\/ Swap the minimum element with first element from unsorted part, unless they are the same\n            if(i != minIndex) {\n                System.out.print(&quot;Found minimum: &quot; + data[minIndex] + &quot;, swapping with &quot; + data[i] + &quot; =&gt; &quot;);\n                temp = data[minIndex];\n                data[minIndex] = data[i];\n                data[i] = temp;\n            }\n            else\n                System.out.print(&quot;Minimum: &quot; + data[minIndex] + &quot; is on the right spot, no swapping =&gt; &quot;);\n            printArray(data);\n        }\n    }\n\n    \/\/ Function to print an array\n    public void printArray(int data[])\n    {\n        for (int i = 0; i &lt; data.length; i++)\n            System.out.print(data[i] + &quot; &quot;);\n        System.out.println();\n    }\n}<\/code><\/pre>\n<p>&nbsp;<\/p>\n<p><strong><u>Main.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">import sorting.SelectionSort;\n\npublic class Main {\n    public static void main(String[] args) {\n        int dataToSort[] = { 6, 5, 4, 2, 3, 1, 7 };\n        SelectionSort selectionSort = new SelectionSort();\n        System.out.print(&quot;Input: &quot;);\n        selectionSort.printArray(dataToSort);\n        selectionSort.sort(dataToSort);\n        System.out.print(&quot;Sorted: &quot;);\n        selectionSort.printArray(dataToSort);\n    }\n}<\/code><\/pre>\n<p>The output of this example is:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-3531 size-full\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/06\/sorting-algoritms-selection-sort-vystup-770-560.webp\" alt=\"selection sort example in java\" width=\"770\" height=\"560\" srcset=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/06\/sorting-algoritms-selection-sort-vystup-770-560.webp 770w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/06\/sorting-algoritms-selection-sort-vystup-770-560-300x218.webp 300w, https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/06\/sorting-algoritms-selection-sort-vystup-770-560-768x559.webp 768w\" sizes=\"auto, (max-width: 770px) 100vw, 770px\" \/><\/p>\n<p>We have prepared the files with the above example as code that you can run directly in Java. Download <a href=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2024\/06\/SelectionSort.zip\" target=\"_blank\" rel=\"noopener\"><strong>SelectionSort Java code<\/strong><\/a>.<\/p>\n<p>If you&#8217;re a <a href=\"https:\/\/msg-life.sk\/en\/jobs\/java-programmer-senior\/\" target=\"_blank\" rel=\"noopener\">Java developer<\/a> looking for a job, check out our <a href=\"https:\/\/msg-life.sk\/en\/benefits\/\" target=\"_blank\" rel=\"noopener\">employee benefits<\/a> and respond to our <a href=\"https:\/\/msg-life.sk\/en\/jobs\/\" target=\"_blank\" rel=\"noopener\">job offers<\/a>!<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article you will learn what selection sort is, how it works, its advantages and disadvantages, and a Java code example.<\/p>\n","protected":false},"author":14,"featured_media":3526,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[57],"tags":[],"class_list":["post-4270","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java"],"acf":[],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/4270","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/comments?post=4270"}],"version-history":[{"count":11,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/4270\/revisions"}],"predecessor-version":[{"id":9702,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/4270\/revisions\/9702"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media\/3526"}],"wp:attachment":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media?parent=4270"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/categories?post=4270"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/tags?post=4270"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}