×

Selection Sort Using Python

Selection sort is a type of sorting algorithm which is based on sorting elements in increasing order or ascending order through comparison. This sorting technique does not take extra space except for one memory space which is used for storing the temporary variable. It is a type of in-place sorting that does not require extra memory space and gives the output in the same memory in which the input was stored.

The time complexity of the selection sort is n2,where n is the number of elements. It uses an iterative method to sort the list. Selection sort divides the list into two parts. One is a sorted list that initially contains no elements, and another one contains an unsorted list that, by default, contains all the elements initially.

Working of Selection Sort

  1. First, we will set the first element as a minimum.
  2. After that, we will compare the minimum value with the second. If the second value is smaller than the minimum value, assign the second element as the minimum value.
  3. We will repeat this for all the elements. We will compare all elements with the minimum value, and the smaller one will be assigned as the minimum value.
  4. After the first iteration, we will get the minimum value of the list. We will swap the minimum value with the first element.
  5. We will set the second element as a minimum and repeat the above steps.
  6. After n-1 iterations, where n is the number of elements, we will get a sorted list.

Code for selection sort

def selection_sort( listvalues ):
    n = len( listvalues )
    for i in range( n - 1 ): 
        min_val_index = i


        for j in range( i + 1, n ):
            if listvalues[j] < listvalues[min_val_index] :
                min_val_index = j


        if min_val_index != i :
            temp = listvalues[i]
            listvalues[i] = listvalues[min_val_index]
            listvalues[min_val_index] = temp


    return listvalues




l = [69,11,9,53,2]


print(selection_sort(l))

Output

[2, 9, 11, 53, 69]

Explanation

In the above code, we have used a list l with random elements like 69, 11, 9, 53, and 2. We have used that list as an argument sent to the selection_sort function. Inside the selection_sort function, we have used two for-loops. The first for loop or the outer for loop is used for keeping count of the iterations, and the inner for loop is used for iterating the elements and finding the minimum value. There is a conditional statement too inside the first for loop. The if-statement inside the outer for loop is used for swapping the actual minimum value with the stored minimum value.

Inside the first iteration, the total number of comparisons is n-1. After that, in the second iteration, the total number of comparisons is n-2. In the third iteration, the total number of comparisons is n-3. Similarly, at the n-1th iteration, the number of comparisons will be n-(n-1), which is 1.

Total comparison: (n-1) + (n-2) + (n-3) + ……+ 2 + 1 = n2

Complexity of selection Sort

Best Case : O(n2)

The best case occurs in selection sort when the list is almost sorted. In that case, the number of comparisons is less.

Average Case: O(n2)

The average case occurs in selection sort when mixed order of elements present in the list, increasing and decreasing.

Worst Case: O(n2)

The worst case occurs in selection sort when the list is sorted in opposite order or, in other words, when the list is sorted in decreasing order. In that case, there will be a total n2 comparison.

Space Complexity: O(1)

The space complexity of the selection sort is constant or linear because it is an in-place sorting algorithm and does not require extra space for storing the output.

Advantages of Selection Sort

These are some of the following advantages of the selection sort

  • It performs very well on lists with less number of elements.
  • It is an in-place algorithm which means it does not require a lot of space for sorting. Only one extra space is required, which is used for storing the temporary variable.
  • It performs very well when the list is sorted or partially sorted.

Disadvantages of Selection Sort

These are some of the following disadvantages of the selection sort.

  • It does not perform well when working on a list with many elements.
  • The number of iterations made during the sorting is n2, where n is the number of elements in the list.
  • Other algorithms have better performance compared to the selection sort.

Related Topics

Convert XML to JSON in Python

XML conversion is very useful if we work on an API that returns data in JSON format and the source of data is in XML format. JSON A JSON file reserves the...

4 minutes read.

Comment starts with the symbol in Python

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

Find whether the given stringnumber is palindrome or not

Problem statement Sam is found of playing with strings. One day he thought of finding whether a string is a palindrome or not. He wanted to develop a computer process to...

2 minutes read.

How to Take Input in Python

How To Take Input In Python Python has various in-built functions that help in code redundancy. Let's discuss the usage of some functions- ascii() – it returns a readable representation of objects.format()...

4 minutes read.

How to run a Program in Python

How to run a Program in Python Writing a program in Python is an easy task, beginners who are ready to kickstart their career in the world of programming can create...

3 minutes read.

List Assignment Index out of Range in Python

As we know, a List is one of the four unique data structures available in Python; In this tutorial, we will deep dive into understanding iterating through a list and...

3 minutes read.

Python String Lowercase

Python Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Write Text files in Python

Let's discuss writing the text file in detail. Generally, writing text also follows the same procedure as like reading text. It varies only in some specific places. Steps followed for writing...

4 minutes read.

How to Practice Python Programming

Learning python kkis a step towards coding. Python gets one closer to programming languages. It is essential to practice every programming language to become a professional in coding. It is...

4 minutes read.

Python vars() Function

Python vars() Function The vars() function in Python returns the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute. Syntax vars([object]) Parameter object: This parameter represents any object with a __dict__attribute Return This function returns...

1 minute read.

Python globals() function

Python globals() function The globals() function in Python returns the value of the named attribute of object where the ‘name’ must be a string. Syntax globals() Parameter NA Return This function returns the global symbol table as a dictionary. Example...

1 minute read.

Python Syntax

Python is a strong object-oriented programming language that is simple to learn. Python was created to be a very readable programming language. The syntax of the Python programming language is...

8 minutes read.

Convert string into int in Python

String A string is defined as a series of characters, special characters, and numbers. A string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. The latter may allow its elements...

2 minutes read.

Python Set Methods

[et_pb_section][et_pb_row][et_pb_column type="4_4"][et_pb_text] Python Set Methods A set is a collection which is unordered and unindexed. Python has a set of built-in methods that you can use on sets. Methods ...

4 minutes read.

Best Database in Python

In this tutorial, Firstly, we will understand what the term database means. Further, we will see the various databases supported in Python and when to use which one. Further, we...

7 minutes read.

Important Difference between Python 2.x and Python 3.x with Example

The comparison between Python 2 and Python 3 is given in the article that follows. Python is a computer language that can perform more tasks than other languages and is...

5 minutes read.

How to Add Elements in List in Python?

How to Add Elements in List in Python We all are aware of the wide spectrum of applications where the data structures of Python are used. Be it lists, tuples, or...

4 minutes read.

Reverse a Number in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

4 minutes read.

How to set font for Text in Python

As a tuple with the font family as the first component, a size in point as the second, and possibly a string with one or more of the style modifiers...

5 minutes read.

Imread Python

In this walkthrough, we'll go over the specifics of using the imread() method of OpenCV-Python and various methods for loading images. Imread is an Image reading library. One of the most helpful...

7 minutes read.