Selection Sort in Python
In this tutorial, we will implement the selection sort algorithm in Python. It is quite straightforward algorithm using the less swapping.
In this algorithm, we select the smallest element from an unsorted array in each pass and swap with the beginning of the unsorted array. This process will continue until all the elements are placed at right place. It is simple and an in-place comparison sorting algorithm.
Working of Selection Sort
The following are the steps to explain the working of the Selection sort in Python.
Let's take an unsorted array to apply the selection sort algorithm.
[30, 10, 12, 8, 15, 1]
Step - 1: Get the length of the array.
length = len(array) → 6
Step - 2: First, we set the first element as minimum element.
Step - 3: Now compare the minimum with the second element. If the second element is smaller than the first, we assign it as a minimum.
Again we compare the second element to the third and if the third element is smaller than second, assign it as minimum. This process goes on until we find the last element.
Step - 4: After each iteration, minimum element is swapped in front of the unsorted array.
Step - 5: The second to third steps are repeated until we get the sorted array.
Selection Sort Algorithm
The selection sort algorithm as follows.
Selection Sort Program using Python
The following code snippet shows the selection sort algorithm implementation using Python.
The sorted array is: [3, 6, 9, 21, 33]
Let's understand the above code -
Time Complexity of Selection Sort
Time complexity is an essential in term of how much time an algorithm take to sort it. In the selection sort, there are two loops. The outer loop runs for the n times (n is a total number of element).
The inner loop is also executed for n times. It compares the rest of the value to outer loop value. So, there is n*n times of execution. Hence the time complexity of merge sort algorithm is O(n2).
The time complexity can be categorized into three categories.
JavaTpoint offers too many high quality services. Mail us on [email protected], to get more information about given services.
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected]
Duration: 1 week to 2 week