Selection Sort in PythonIn 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 SortThe 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 AlgorithmThe selection sort algorithm as follows. Algorithm Selection Sort Program using PythonThe following code snippet shows the selection sort algorithm implementation using Python. Code – Output: The sorted array is: [3, 6, 9, 21, 33] Explanation – Let’s understand the above code –
Time Complexity of Selection SortTime 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. |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263209.html