Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

( Python ) Can you swap the starting process of the selection sort?

from finding the minimun and put it on the left to finding the maximum and put it on the right

def SelectionSort(a_list):
    n = len(a_list)

    for i in range(0, n-1):
        iMin = i
        print(a_list)

        for j in range(i+1, n):
            if a_list[j] < a_list[iMin]:
                iMin = j

        temp = a_list[i]
        a_list[i] = a_list[iMin]
        a_list[iMin] = temp
    
    print()
    return a_list

someList = [45,984,6,90,8946,89]
SelectionSort(someList)

Can it swap the process from minimum => maximum to minimum <= maximum

the answer should look like this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[6, 45, 89, 89, 984, 8946]

>Solution :

Yes:

  • Rename iMin to iMax
  • Mirror the two ranges you use:
    • range(0, n-1) becomes range(n-1, 0, -1)
    • range(i+1, n) becomes range(i-1, -1, -1)
  • Mirror the comparison operator
    • < becomes >

Result:

def SelectionSort(a_list):
    n = len(a_list)

    for i in range(n-1, 0, -1):
        iMax = i
        print(a_list)

        for j in range(i-1, -1, -1):
            if a_list[j] > a_list[iMax]:
                iMax = j

        temp = a_list[i]
        a_list[i] = a_list[iMax]
        a_list[iMax] = temp
    
    print()
    return a_list

Unrelated to your question (and as commented), swapping can be done like this:

    a_list[i], a_list[iMax] = a_list[iMax], a_list[i]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading