×

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 does the if __name__ == "__main__" do in Python

In this article, you will learn about the If__name__==__main__ is a statement in python to define modules and the names of the modules. This statement plays a vital role in...

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.

Read Text files in Python

In Python, there are many ways to read text files. Before going into the detailed structure of reading a text file, let us understand how reading text files takes place...

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.

Python coding platform

Python is a popular general-purpose programming language with many applications. High-level data structures, datatypes, dynamic binding, and many other features make it useful for both designing complex applications and "glue...

6 minutes read.

Python String rjust() method

Python String rjust() method The string.rjust() method in Python returns a right-justified string of a given minimum width where the padding is done using the specified fillchar (default is a space). It returns...

2 minutes read.

Map Syntax in Python

Introduction: In Python, a function called map acts as an iterator, returning a result after each item in an iterable has been subjected to a function (tuple, lists, etc.). When you...

6 minutes read.

Executing Shell Commands in Python

This tutorial aims to make us understand what a Shell is, what is the importance of a Shell, what are Shell commands in Python, and how can we execute the...

3 minutes read.

Python System Requirements

Introduction As we know, Python is a popular programming language usually used to write scripts for operating systems. It’s handy adequate for utilizing in web development and application design. In this article,...

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.

Python Dictionary items() method

Python Dictionary items() method The dictionary.items() method in Python returns a view object that displays a list of dictionary's (key, value) tuple pairs. Syntax dictionary.items() Parameter NA Return This method returns a view object, displaying the list...

1 minute read.

Python Dictionary pop() method

Python Dictionary pop() method The dictionary.pop() method in removes the specified item and returns an element from a dictionary having the given key. Syntax dictionary.pop(key[, default]) Parameter key – This argument signifies the key which is to...

2 minutes read.

AX Contour in Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

What is Sleeping Time in Python

Did you ever postpone a Python program's execution? Usually, you want your code to execute as quickly as possible. But there are times when it is in your best interests...

3 minutes read.

Sys Module in Python

What are Modules? The Modules are the kind of files that contain Python statements and definitions. The module is known by the name of the file followed by the suffix “.py”....

5 minutes read.

Closest Pair of Points in Python

We are given an array of n points in the plane, and our task is to find the pair of points in the array that are the closest to each...

3 minutes read.

Allocate a minimum number of pages in python

You have given a sorted array of size n which represents the number of pages in n different books and an integer value which denotes the number of students. We...

4 minutes read.

End Parameter in python

print(): The python print() function prints the program’s output to the output screen. The output can be an integer value, string value or other value. Syntax: print(“hi”) Output: hi will be displayed on the output...

3 minutes read.

Convert String to Binary in Python

String to binary The strings can be defined as the array of Unicode code characters. Binary Binary is defined as the number system which consists two symbols 0 and 101. It is base-2...

2 minutes read.

Standard GUI Unit Converter using PyQt5 in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

6 minutes read.