1

I wrote a selection sort implementation that doesn't work. I can't figure out why.

#!/usr/bin
def sel_sort(list):
    for i in xrange(n-2):
        imin=i
        for j in xrange(i+1,n-1):
            if list[j]<list[imin]:
                imin=j
        list[imin],list[i]=list[i],list[imin]

n=int(raw_input("Enter number of elements : "))
x=[]
for t in xrange(n):
    x.append(int(raw_input()))

sel_sort(x)

for k in xrange(n):
    print x[k],

Also could anyone explain why I should place #!/usr/bin at the beginning of this program?

5
  • 1
    Can you provide some more details? Commented Mar 14, 2017 at 16:21
  • 1
    The first line should read #!/usr/bin/env python. It's a hashbang, or shebang. The algorithm is buggy though Commented Mar 14, 2017 at 16:25
  • @slezica This should work though. Commented Mar 14, 2017 at 16:26
  • 1
    Note: Don't use list as a variable name, as it is a Python function. Commented Mar 14, 2017 at 16:30
  • got that thanks. @MartinEvans Commented Mar 14, 2017 at 16:32

1 Answer 1

1

With your code, after every other iteration the following was the result,

[0, 3, 77, 25, 87, 22, 12, 7, 2, 43]
[0, 2, 77, 25, 87, 22, 12, 7, 3, 43]
[0, 2, 3, 25, 87, 22, 12, 7, 77, 43]
[0, 2, 3, 7, 87, 22, 12, 25, 77, 43]
[0, 2, 3, 7, 12, 22, 87, 25, 77, 43]
[0, 2, 3, 7, 12, 22, 87, 25, 77, 43]
[0, 2, 3, 7, 12, 22, 25, 87, 77, 43]
[0, 2, 3, 7, 12, 22, 25, 77, 87, 43]
[0, 2, 3, 7, 12, 22, 25, 77, 87, 43]
0 2 3 7 12 22 25 77 87 43

As you can clearly see, it ignores the last element!

xrange basically generates from start to end-1 (xrange(start,end))!

The inner loop should be of range i+1 to n and not n-1

def sel_sort(list):
    for i in xrange(n-2):
        imin=i
        #here range is i+1 to n
        for j in xrange(i+1,n):
            if list[j]<list[imin]:
                imin=j
        list[imin],list[i]=list[i],list[imin]
        print list

Example,

Input:

x=[7, 3, 77, 25, 87, 22, 12, 0, 2, 43]

Output:

0 2 3 7 12 22 25 43 77 87

The use of #!/usr/bin at the beginning of this program can be well understood by wiki link shared in comments. This would give a clear insight about the same!

Hope it helps!

Sign up to request clarification or add additional context in comments.

3 Comments

Yes! Thank You Keerthana, but could you provide details why i+1 to n and not n-1 ?
because you were ignoring the last element while iterating! I've added the edits! Did that answer you question?
xrange(N) generates numbers from 0 to N -1 (not N). Consequently xrange(n-2) provides numbers form 0 to n-3 etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.