Reputation: 53
So i'm supposed to take in a number n, add n numbers to a list, then sort the list and print.
numCol=int(input());
vals=[];
for x in range(numCol):
vals.append(int(input()))
for x in range(len(vals)):
curr=vals[x];
for y in range(x+1,len(vals)):
if(curr>vals[y]):
temp=vals[y];
vals[y]=curr;
vals[x]=temp;
print(vals);
the code doesn't work properly. We haven't learned sorting algorithms thoroughly really yet, so i'm kinda just making my own, but it resembles selection sort I think. Anyways, why is it not printing the values in ascending order?
Edit: I input 4, then make list 4, 3, 2, 1. Output is [1, 4, 4, 4]
Upvotes: 0
Views: 91
Reputation: 391
You're welcome -
numCol=int(input());
vals=[];
for x in range(numCol):
vals.append(int(input()))
for x in range(len(vals)):
for y in range(x+1,len(vals)):
if(vals[x]>vals[y]):
temp=vals[y]
vals[y]=vals[x]
vals[x]=temp
print(vals)
The problem was that you weren't changing the value of cur to be compared correctly.
Edit - Just saw other answers had beat me to it :(
Upvotes: 0
Reputation: 7706
Change this part of code
for x in range(len(vals)):
curr=vals[x];
for y in range(x+1,len(vals)):
if(curr>vals[y]):
temp=vals[y];
vals[y]=curr;
vals[x]=temp;
To this:
for x in range(len(vals)):
for y in range(x+1,len(vals)):
if(vals[x]>vals[y]):
temp=vals[y];
vals[y]=vals[x];
vals[x]=temp;
Upvotes: 1
Reputation: 6259
You can solve sorting of lists much easier and in a more pythonic way, simply use the sort command, here is an example:
import random
a=random.sample(range(30), 10)
print a
a.sort()
print a
Upvotes: 0
Reputation: 3818
the problem is curr
should change after swap.
for x in range(len(vals)):
curr=vals[x];
for y in range(x+1,len(vals)):
if(curr > vals[y]):
temp = vals[y]
vals[y] = curr
vals[x] = temp
curr = vals[x] # <--
Upvotes: 1