Discussion Room : IDC101

Sort algorithm

Sort algorithm

by Dr. Amit Kulshrestha -
Number of replies: 1

Situation: A number of students are standing in a queue.

Task: We wish to shuffle these students so that at the end, the queue is sorted by height, with the shortest student occupying first position while the tallest one occupying the last position.

Algorithm: Compare the height of student standing at first position with everyone else and swap the positions of two if they are standing in undesired order of height. This will ensure that shortest student occupies first position in the queue. Now compare the height of student standing at second position with everyone behind him and swap the positions of two if they are standing in undesired order of height. Keep doing this, starting third, fourth, fifth,...., (n-1)st student. Eventually the queue will be sorted in the desired order.

Convert this code into Python and share.

It will be great if students can share other algorithms to accomplish the task of sorting.

Keep Pythoning!

In reply to Dr. Amit Kulshrestha

Re: Sort algorithm

by Rutvik Kayastha -

def s1(list1):

    for i in range(len(list1)-1):

        for j in range(len(list1)-i):

            if list1[i]>list1[i+j]:

                list1[i],list1[i+j]=list1[i+j],list1[i]

                print list1

if u don't want to see process then indent print,I am not so sure about code,try it on various lists.but atmost it's true.

Attachment My work.JPG