DEV Community

loading...

Day 46 Of 100DaysOfCode: More About Selection Sort

iamdurga profile image Durga Pokharel Updated on ・2 min read

Today is my 46th day of 100daysofcode and python. Like yesterday today also continued to learned more about algorithm. Time and space complexity of selection sort.

To do selection sort we repeatedly finding the minimum element from unsorted array and putting it to the beginning.

Selection Sort

Selection sort is simple sorting algorithm. It is an in place comparison sorting algorithm.

A = [53,45,23,10,4]
for i in range(len(A)):
    min_idx = i
    #print(i)
    for j in range(i + 1,len(A)):
        A[min_idx] > A[j]
        min_idx = j
        A[i],A[min_idx] = A[min_idx],A[i]
    print(f'Current array : {A}.')
print('sorted array:')
for i in range(len(A)):
    print('%d'%A[i])
Enter fullscreen mode Exit fullscreen mode

Step1

Take original array. Here minimum element in the array is 4. Now put 4 in the beginning. New array is,
4 45 23 10 53

Step2

Now we left element at the index first so take the remaining array choose minimum one. Here minimum element is 10 now put it to the origin. New array is,
4 10 23 45 53
Now obtained array is completely sorted.
Output of the above program is,

Current array : [4, 53, 45, 23, 10].
Current array : [4, 10, 53, 45, 23].
Current array : [4, 10, 23, 53, 45].
Current array : [4, 10, 23, 45, 53].
Current array : [4, 10, 23, 45, 53].
sorted array:
4
10
23
45
53
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide