Page 1 of 1

Sorting Problem

Posted: Sun Apr 25, 2004 7:38 pm
by Jonathon
I am stuck on a sort problem. I am not able to get them to sort in acending order correctly. Unfortunetly I cannot use a swap command in my problem.

So far I have:

Dim number$(20)
Dim class$(20)
for t = 1 to 4
Read number$(t), class$(t)
next t

for x = 1 to 15
      if number$(x) > number$(x+1) then
      temp = number$(x)
      number$(x) = number$(x + 1)
      number$(x + 1) = temp
      print number$(x), class$(x)
end if
next x



thanks, any help would be appreciated. Still trying to learn QB.

Re: Sorting Problem

Posted: Wed Apr 28, 2004 4:22 pm
by frankiebaby
Hey there Jonathan,
          Is there some reasons that you need to use strings to store your numbers? I would assume so, else you probobly would not have used them. The thing is, thaey are why it is not sorting correctly. When you compare strings, it compares them letter by letter. I think this may be the cause, as u are not comparing them by number. Becuase of this:

imagine this set: 10, 15, 105
sorting as strings probobly yields: 10, 105, 15
why? the ones are the same 1x, 1x, and 1xx
when the next character is compared, the 10, 5 and 0 are compared, so, the 105 would switch with the 15, becuase zero comes before 5.

to fix this, sort by number:
     the VAL keyword converts a string containing a number into a value:


Dim number$(20)
Dim class$(20)
for t = 1 to 4
Read number$(t), class$(t)
next t

for x = 1 to 15
 if VAL(number$(x))> VAL(number$(x+1) then
 temp$ = number$(x)
 number$(x) = number$(x + 1)
 number$(x + 1) = temp
 print number$(x), class$(x)
end if
next x

Re: Sorting Problem

Posted: Wed Apr 28, 2004 6:24 pm
by Jonathon
hey, thanks a lot. That really helped.

Re: Sorting Problem

Posted: Sat May 01, 2004 6:02 pm
by Jonathon
I did that and have to trouble with the first set sorting and printing, but the second variable doesnt follow. How can I get it to follow through the sorting with the first?