-2
\$\begingroup\$

I'm following the pseudocode as given as a part of an excercise in CLRS.

Consider sorting \$n\$ numbers stored in array \$A\$ by first finding the smallest element of \$A\$ and exchanging it with the element in \$A[1]\$. Then find the second smallest element of \$A\$, and exchange it with \$A[2]\$. Continue in this manner for the first \$n-1\$ elements of \$A\$.

a = [99, 31, 41, 59, 26, 42, 58]

for i in range(0, len(a)):

    min = a[i]

    for j in range(i, len(a)):

        if a[j] < min:
            min = a[j]
            a[j] = a[i]
            a[i] = min
\$\endgroup\$
  • \$\begingroup\$ Welcome to Code Review! I changed the title so that it describes what the code does per site goals: "State what your code does in your title, not your main concerns about it.". Feel free to edit and give it a different title if there is something more appropriate. \$\endgroup\$ – Sᴀᴍ Onᴇᴌᴀ Jan 9 '18 at 23:58
1
\$\begingroup\$

If you want us to evaluate your code in light of the pseudocode, you'll have to provide the pseudocode, too.

That said, it seems like you're doing a lot of extra work. Specifically, whenever you find an a[j] < min you're swapping the a[j] and a[i] values. The description you give of the pseudocode says to find the min, and then swap. That would be a single swap once the j loop is done. You might need a separate variable to hold the index of the min, too:

if a[j] < min:
    mindex = j
    min = a[j]
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.