Computer Science Canada

Sorting to an Array

Author:  ssikmace [ Fri Apr 02, 2004 12:04 pm ]
Post subject:  Sorting to an Array

How can I get my program to read a list and sort it alphebetically to an array.

var streamin : int
var nameCount : int
var name : string

open : streamin, "Names.txt", get
assert streamin > 0

nameCount:= 0
loop
get : streamin, skip
exit when eof(streamin)
get : streamin, name
nameCount:= nameCount + 1
end loop

close (streamin)

open : streamin, "Names.txt", get
assert streamin > 0

var Names : array 1..nameCount of string
for i : 1..nameCount
get : streamin, Names(i)
end for

close (streamin)

for i : 1..nameCount
put Names(i)
end for

Author:  Raugrist [ Fri Apr 02, 2004 2:38 pm ]
Post subject: 

There are different ways of sorting arrays. Probably the easiest would be the bubble sort. With your code it would look something like:

code:

var tempName : string

for i : 1 .. nameCount - 1
    for j : i + 1 .. nameCount
        if Names (j) < Names (i) then
            temp := Names (j)
            Names (j) := Names (i)
            Names (i) := temp
        end if
    end for
end for

Of course it's been a while since I've had to sort something, so it'd be best for you to check out the sorting lesson in the tutorial's section.

Author:  Delos [ Fri Apr 02, 2004 5:04 pm ]
Post subject: 

Look around for Catalyt's TuringLib.

It has quick sort in it...so you'll be set...

But if you're new at Turing, your teacher won't believe you made a q-sort. In that case stick w/ the bubble sort...of which everyone knows something about.

Author:  ssikmace [ Mon Apr 05, 2004 6:52 pm ]
Post subject: 

great thx Very Happy


: