×

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

Python type() Function

Python type() Function The type() function in Python returns the type of an object. The return value is a type object and generally the same object as returned by object.__class__. Syntax class type(object)      ...

1 minute read.

Python String rindex() method

Python String rindex() method The string. rindex() method in Python returns the highest index of the substring inside the string (if found). If the substring is not found, it raises an...

2 minutes read.

Data Distribution in python

Before discussing data distribution, we will discuss each word that is data and Distribution. What is meant by data? A collection of raw facts and figures is called data. The word "raw"...

18 minutes read.

Sort a dataframe based on a column in Python

Sorting the dataframe based on a column requires pandas which is An open-source library called Python Pandas is described as offering high-performance data processing in Python. For both professionals and...

4 minutes read.

Python List count() method

Python List count() method The list.count() method returns the number of times x appears in the list. Syntax list.count(x) Parameter x: This parameter represents the value to search for and can contain any iterable (list, set, tuple, etc.) Return This method returns the...

1 minute read.

Python lock

Before understanding the concept of Python-lock we need to understand what kind if condition we require to implement the locks in Python. Let us start with multithreading and its implementation...

5 minutes read.

Subprocess Module in Python

What is a Process? Every program will have its respective system state, i.e., the state in which it is running. A program that is in a running state or in a...

7 minutes read.

Python filter() function

Python filter() function The filter() function constructs an iterator from those elements of iterable for which the parameter ‘function’ returns a Boolean value true. Syntax filter(function, iterable) Parameter function: This parameter represents a function to be run for each item in the...

1 minute read.

Python Stack

Python Stack: The work Stack is defined as arranging a pile of objects or items on top of another. It is the same method of allocating memory in the stack...

10 minutes read.

Best Way to Learn Python for Free

Python is a booming language these days. It has many applications for making code easier; it is also an open-source language. Learning Python is a step towards coding. Python gets...

5 minutes read.

Difference between Python 2 and Python 3

In this tutorial, we will learn the differences between two versions of python, that is, python version 2 and python version 3. Some basic differences include- Python 2 is the older version...

3 minutes read.

Python Struct

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.

Sklearn in Python

Scikit-learn or sklearn is a machine learning library used in Python that provides many unsupervised and supervised learning tools and algorithms. David Cournapeau first created it as a 2007 Google...

7 minutes read.

Python program to display ASCII value of the character

Python program to display ASCII value of the character The full form of ASCII is American Standard Code for Information Interchange. This example explains a program in Python to find the...

1 minute read.

Weight Conversion GUI using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

How to print in same line in python

How to Print in the Same Line in Python To print in Python, we use the print () function and the syntax of print () goes like this: print (values, sep =...

3 minutes read.

Python Project Ideas

One of the most widely used programming languages today is Python. This pattern appears set to continue through 2023 and beyond. Therefore, working on some current Python project ideas is the...

10 minutes read.

Python Matrix Operations

Python Matrix In this section of the Python tutorial, we will look at the introduction of the matrix in Python programming. We will perform many operations on the Python matrix using...

21 minutes read.

Python issubclass() Function

Python issubclass() Function The issubclass() function in Python returns a boolean value ‘True’ if the given object is a subclass of classinfo, else it returns False. Syntax issubclass(class, classinfo) Parameter class: It is a required parameter which represents a tuple...

1 minute read.

Python Program to find the length of a string

Python program to find the length of a string A string in Python is a set of Unicode characters. It can't be changed once it's been declared. The number of characters...

2 minutes read.