Hi guys, I have written this program so far which reads and sorts numbers from a file...WITHOUT the sort function. It sorts from largest to smallest right now.

My Question:
How do I make my program list the numbers from smallest to largest instead?

File contains the following:
2 1 5 10 8
3 900
47 6 11

Program:

scores = [0,0,0,0,0,0,0,0,0,0]
result = [0,0,0,0,0,0,0,0,0,0]
file = open("test.txt","r")
lines = file.readlines()
file.close()
count = 0
result_index = 0
largest = 0
if (lines):
    for line in lines:
        s = line.split()
        for score in s:
            scores[count] = int(score)
            count = count + 1
    while (result_index < count):
        smallest = scores[9]
        for i in range(0,count):
            if scores[i]+1 > smallest:
                smallest = scores[i]
                index_of_smallest = i
        result[result_index] = smallest
        scores[index_of_smallest] = largest + 1
        result_index = result_index + 1
else:
        print "no data in the file!"
print "result is ",result

shell output:

result is  [900, 47, 11, 10, 8, 6, 5, 3, 2, 1]

I am not allowed to use a sort function unfortunately....

otherwise the whole program would be much shorter obviously.

here is one i made that works:

f = open("test.txt","r")
text = f.readlines()
f.close()

lines = []
for line in text:
        s = line.split()
        for score in s:
            lines.append(int(score))
           
for line in range(1, len(lines)):
    key = lines[line]
    i = line - 1
    while (i >=0) and (lines[i] > key):
        lines[i+1] = lines[i]
        i = i - 1
    lines[i+1] = key

print lines

Yeah looks like it works, thanks a lot!

But I wonder, is there any modification that can be made to my own version that will make it work too?

You could just reverse your list at the end to sort it the other way around.

That works too I suppose.

I'm somewhat unfamiliar with your style of the program, since I haven't utilized 3 "for loops" so far. It's certainly more efficient.

How would I change your version to also print like my original version as well? In other words, large to small?

I just inserted this just before the print line statement:

lines.reverse()

Then when it prints it goes from largest to smallest.

Hope that helps

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.