# Write a selection sort algorithm python

Happy Pythoning! During these comparisons, if a smaller element is found then that is considered the new minimum.

As the algorithm proceeds, the sorted portion of the list will grow and the unsorted portion will continue to shrink. Algorithm Consider the first element to be sorted and the rest to be unsorted Assume the first element to be the smallest element.

How Selection Sort Works?

## Selection sort in python with user input

This process continues till all the elements are sorted. This sorting algorithm is an in-place comparison-based algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted part at the right end. Similar to Insertion Sort, we begin by considering the first element to be sorted and the rest to be unsorted. A slice from a list actually allocates a new list; our code here doesn't need a new list, it just needs a convenient way to examine a sublist. We find that 14 is the second lowest value in the list and it should appear at the second place. Now that you have a fair understanding of what Selection Sort is, let us take a look at the algorithm and its code. Now consider the second element in the list to be the smallest and so on till all the elements in the list are covered. We use the standard Python idiom for swapping two values. After two iterations, two least values are positioned at the beginning in a sorted manner. If there is a tie, min will use the second part of the tuple, the index, as a tie-breaker. NOTE: Once an element is added to the sorted portion of the list, it must never be touched and or compared.

But we don't actually care about the min value; we care about the index. Now consider the second element in the list to be the smallest and so on till all the elements in the list are covered.

After one iteration 10, which happens to be the minimum value in the list, appears in the first position of the sorted list. Now that you have a fair understanding of what Selection Sort is, let us take a look at the algorithm and its code.

### Simple python program for selection sort

But for sort we don't care how ties are broken. After two iterations, two least values are positioned at the beginning in a sorted manner. How to implement Selection Sort? Now that you have a fair understanding of what Selection Sort is, let us take a look at the algorithm and its code. Check if the first element is smaller than each of the other elements: If yes, do nothing If no, choose the other smaller element as minimum and repeat step 3 After completion of one iteration through the list, swap the smallest element with the first element of the list. This process continues till all the elements are sorted. We are in the third tutorial of the sorting series.

The previous tutorial talks about Bubble Sort and Insertion Sort.

Rated 10/10
based on 7 review

Download