×

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

What is Python 2

Python is a widely used high-level language. The initial work on developing python was begun in the late 1980s. In 1989, Guido Van Rossum started to work on it. Initially,...

3 minutes read.

Python Read Excel file

Python Read Excel file Excel is the spreadsheet application for Window, which is developed by Microsoft. The Excel stores data in the tabular form. It provides easy access to analyze and maintain the...

3 minutes read.

Python Coroutine

Introduction In Python, Coroutines are defined as the special type of function that freely allows control to its caller without losing the state. Coroutines and generates are similar but coroutines consist...

3 minutes read.

Introducing modern python computing in simple packages

Python is the language for newly evolving technologies and has become one of the most popular computer languages in the world. Python is used in everything right from a simple...

3 minutes read.

Python File Handling

What is the file? The file is a collection of data in a single unit. It is used to store information in the non-volatile memory such as hard-disk. Computer programs generally run on the RAM...

7 minutes read.

How to Install PIP In Python

How to Install PIP In Python The libraries for Python have made our work easier than we expected. From a simple addition of two numbers to applying algorithms on the big...

4 minutes read.

Excel to CSV in Python

Define MS Excel Microsoft Excel is an application provided by the Microsoft corporation which allows us to build graphs to build tables, and it is also used for the macro programming...

4 minutes read.

Nested List in Python

The list is an inbuilt sequential data type in Python. It is a very useful and frequently used data type. A list can store any number of data items of...

4 minutes read.

Python Web Development projects

What is Python? Python is currently one of the most widely used computer programming languages. This isn't just an exaggeration; Python is the second-most famous programming language on the software development...

3 minutes read.

Not supported between instances of str and int in python

In this article, you are going to learn why the type error occurs between instances of string and integer datatypes. Also, you will know what kind of error is the...

6 minutes read.

How to uninstall python

To un-install Python, we need to follow different procedures in different operating systems. In this article, we will discuss the un-installation process of Python in Windows, Mac, and Linux operating...

4 minutes read.

Python pynmea2

Define Pynmea2 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...

4 minutes read.

Difference between Expression and Statement in Python

What is an expression in Python? Expression is a combination of operands and operators. Expression helps us to produce some other values. In the python programming language,  expressions produce some other value...

6 minutes read.

SKLearn Model Selection

The model selections of SK learn has many functions with which we can work on.It has functions to cross-validate the model and, it also provides validation and learning curves.It is...

3 minutes read.

How to Install Tweepy in Python

In this article, we will learn or understand how to install Tweepy in Python and what Tweepy is. Firstly, let’s understand What Tweepy is. As we all know, one of the...

3 minutes read.

Screen Rotation app Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

3 minutes read.

Exponentiation in Python

What is an Exponent in Python? Exponent is a fundamental mathematical concept that is used in many different areas, such as engineering, physics, and finance. In mathematics, an exponent is a...

4 minutes read.

Python String startswith() method

Python String startswith() method The string.startswith() method in Python returns a boolean value ‘True’ if the given string starts with the prefix, otherwise it returns False. Syntax startswith(prefix[, start[, end]]) Parameter prefix: This parameter signifies the value to check. start(optional):...

1 minute read.

How to check version of Python

How to check version of python The versions of Python come with different kinds of features and functionalities. It is not a herculean task to keep track of the updates these...

3 minutes read.

Sublime Python

SUBLIME: A compact, cross-platform code editor called Sublime Text 3 (ST3) is well-known for its quickness, usability, and robust community support. Although it's a fantastic editor out of the box, its...

6 minutes read.