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.
Sorting Problem
Moderators:Administrator, Global Moderator
- frankiebaby
- Global Moderator
- Posts:95
- Joined:Tue Apr 30, 2002 1:38 am
- Location:Pennsylvania
- Contact:
Re: Sorting Problem
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
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
hey, thanks a lot. That really helped.
Re: Sorting Problem
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?