{"id":12920,"date":"2021-02-22T16:37:08","date_gmt":"2021-02-22T16:37:08","guid":{"rendered":"https:\/\/www.askpython.com\/?p=12920"},"modified":"2021-02-22T16:43:17","modified_gmt":"2021-02-22T16:43:17","slug":"selection-sort-in-python","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/selection-sort-in-python","title":{"rendered":"Selection Sort in Python"},"content":{"rendered":"\n<p>Today we will learn a simple and easy to visualize sorting algorithm called the Selection Sort in Python. Let&#8217;s get started.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The Selection Sort Algorithm<\/h2>\n\n\n\n<p>Similar to <a href=\"https:\/\/www.askpython.com\/python\/examples\/insertion-sort-in-python\" class=\"rank-math-link\">Insertion Sort<\/a>, the insertion sort algorithm divides the list into two parts. The first part at the beginning of the list is the sorted part and the second part at the end of the list is unsorted.<\/p>\n\n\n\n<p>Initially, the entire list is unsorted but with every iteration, the smallest item in the list is searched (for ascending list) and added to the sorted section.<\/p>\n\n\n\n<p>How this happens is that one by one, we find the smallest item in the unsorted section and swap it with the item at its correct position.<\/p>\n\n\n\n<p>So in the first iteration, the smallest item is swapped with the item at the first position. In the second iteration, the second smallest item is swapped with the item at the second position. And so on&#8230;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Implementing Selection Sort in Python<\/h2>\n\n\n\n<p>Below is a simple implementation of selection sort in Python. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\ndef selection_sort(lst):\n    n = len(lst)\n    for i in range(n - 1):\n        min = i\n        for j in range(i + 1, n):\n            if(lst&#x5B;j] &lt; lst&#x5B;min]):\n                min = j\n        lst&#x5B;i], lst&#x5B;min] = lst&#x5B;min], lst&#x5B;i]\n<\/pre><\/div>\n\n\n<p>Notice that the function takes in a list and performs the sorting in-place, it is fairly simple to alter the algorithm to return a sorted list instead.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Explaining the Steps of the Selection Sort Algorithm<\/h2>\n\n\n\n<p>This algorithm sorts the list in increasing order, let us see how it works.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>The variable <code>n<\/code> is the number of items in the list.<\/li><li>Now, <code>i<\/code> goes from <code>0<\/code> to <code>n - 2<\/code>, which means that <code>i<\/code> points from the first item to the second-last item. The role of <code>i<\/code> is that it will always point to where the next smallest item will go, so we will find the smallest item from <code>i<\/code> to the end of the list, and it will be placed at <code>i<\/code>.<\/li><li>We are considering the item at <code>i<\/code> to be the smallest one for now, because if we fail to find a smaller element after <code>i<\/code>, then <code>i<\/code> holds the correct item.<\/li><li>Inside, <code>j<\/code> goes from <code>i + 1<\/code> to <code>n - 1<\/code>, which means that <code>j<\/code> will point to all the items after <code>i<\/code>, and it will be responsible to find the smallest item in that range.<\/li><li>Now we compare the item at <code>j<\/code> to the smallest item we have found yet, and if the item at <code>j<\/code> is smaller, then it becomes the smallest item we have found yet.<\/li><li>After the inner loop, we have found the smallest item from <code>i<\/code> to <code>n - 1<\/code>, and it is swapped with the item at <code>i<\/code> so that it goes to its correct position.<\/li><li>The outer loop will continue to select and place the next smallest items one after the other until the entire list is sorted.<\/li><\/ul>\n\n\n\n<p>Now we will try to dry-run this algorithm on an example and see how it affects the sequence. <\/p>\n\n\n\n<p><strong>Let&#8217;s consider the sequence as 12, 16, 11, 10, 14, 13.<\/strong><br><strong>Size of the given list (n): 6<\/strong><\/p>\n\n\n\n<p>12, 16, 11, <span class=\"has-inline-color has-pale-cyan-blue-color\">10<\/span>, 14, 13<br><span class=\"has-inline-color has-light-green-cyan-color\">10<\/span>, 16, <span class=\"has-inline-color has-pale-cyan-blue-color\">11<\/span>, 12, 14, 13<br><span class=\"has-inline-color has-light-green-cyan-color\">10<\/span>, <span class=\"has-inline-color has-light-green-cyan-color\">11<\/span>, 16, <span class=\"has-inline-color has-pale-cyan-blue-color\">12<\/span>, 14, 13<br><span class=\"has-inline-color has-light-green-cyan-color\">10<\/span>, <span class=\"has-inline-color has-light-green-cyan-color\">11<\/span>, <span class=\"has-inline-color has-light-green-cyan-color\">12<\/span>, 16, 14, <span class=\"has-inline-color has-pale-cyan-blue-color\">13<\/span><br><span class=\"has-inline-color has-light-green-cyan-color\">10<\/span>, <span class=\"has-inline-color has-light-green-cyan-color\">11<\/span>, <span class=\"has-inline-color has-light-green-cyan-color\">12<\/span>, <span class=\"has-inline-color has-light-green-cyan-color\">13<\/span>, <span class=\"has-inline-color has-pale-cyan-blue-color\">14<\/span>, 16<br><span class=\"has-inline-color has-light-green-cyan-color\">10<\/span>, <span class=\"has-inline-color has-light-green-cyan-color\">11<\/span>, <span class=\"has-inline-color has-light-green-cyan-color\">12<\/span>, <span class=\"has-inline-color has-light-green-cyan-color\">13<\/span>, <span class=\"has-inline-color has-light-green-cyan-color\">14<\/span>, <span class=\"has-inline-color has-light-green-cyan-color\">16<\/span><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>The numbers in green are the ones that have been sorted.<\/li><li>The numbers in blue are the smallest ones from the ones that are not sorted.<\/li><li>The uncolored ones are to be sorted.<\/li><\/ul>\n\n\n\n<p>It can be seen that the algorithm finds the smallest items and then swaps them with the item at their correct place.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The Output<\/h2>\n\n\n\n<p>Running the same list on the algorithm will produce the following result:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1021\" height=\"577\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/02\/selection-sort-example.png\" alt=\"Selection Sort Example\" class=\"wp-image-12921\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/02\/selection-sort-example.png 1021w, https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/02\/selection-sort-example-300x170.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2021\/02\/selection-sort-example-768x434.png 768w\" sizes=\"auto, (max-width: 1021px) 100vw, 1021px\" \/><figcaption>Selection Sort in action<\/figcaption><\/figure><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>In this tutorial, we saw how Selection Sort works, we implemented the algorithm in Python and verified the dry-run of an example using the actual output of the code. <\/p>\n\n\n\n<p>Selection Sort, similar to <a href=\"https:\/\/www.askpython.com\/python\/examples\/bubble-sort-in-python\" class=\"rank-math-link\">Bubble<\/a> and Insertion Sort, has a complexity of O(n<sup>2<\/sup>). This means that if the input size is doubled, the time it takes to execute the algorithm increases by four times, and so, it is an inefficient sorting algorithm. <\/p>\n\n\n\n<p>It is generally less efficient than Insertion Sort but it is much simpler to understand and implement. I hope you enjoyed learning about Selection Sort and see you in the next tutorial.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Today we will learn a simple and easy to visualize sorting algorithm called the Selection Sort in Python. Let&#8217;s get started. The Selection Sort Algorithm Similar to Insertion Sort, the insertion sort algorithm divides the list into two parts. The first part at the beginning of the list is the sorted part and the second [&hellip;]<\/p>\n","protected":false},"author":24,"featured_media":12923,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1,9],"tags":[],"class_list":["post-12920","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","category-examples"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/12920","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/24"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=12920"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/12920\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/12923"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=12920"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=12920"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=12920"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}