PDA

View Full Version : sorting array



mombasa
- 8th May 2017, 20:33
Hi, i would need help to solve a problem. I have 9 variables that contain the penalties found in a car race. I have to put them in ascending order and form a ranking by keeping the variable name or assigning a new one but without losing the reference to the starting variable. I tried it with an array but in this way I get the array values sorted but I lose the link to the variable name. Is there a way to sort the array while keeping the link to the name of the individual variable? Thanks.


car1/car9 variable

starting situation

car1=54 penalty
car2=81
car3=25
car4=14
car5=6
car6=29
car7=77
car8=32
car9=44

after sorting

1) car5
2) car4
3) car3
4) car6
5) car8
6) car9
7) car1
8) car7
9) car2

richard
- 9th May 2017, 12:26
this works


'car1=54 penalty
' car2=81
' car3=25
' car4=14
' car5=6
' car6=29
' car7=77
' car8=32
' car9=44

num_cars con 9
cars var byte[num_cars*2]
carw var word ext
tmp var word
sw_flag var bit
car_cnt var byte
car_cnter var byte
DEFINE DEBUG_REG PORTB
DEFINE DEBUG_BIT 7
DEFINE DEBUG_BAUD 9600
DEFINE DEBUG_MODE 0
pause 2000
Debug "Start",13 ,10
@carw = _cars
arraywrite cars,[1,54,2,81,3,25,4,14,5,6,6,29,7,77,8,32,9,44]

car_cnt =0
while car_cnt < num_cars
debug 13,10,#carw[car_cnt]//256,9,#carw[car_cnt]/256
car_cnt =car_cnt +1
wend
gosub sort
car_cnt =0
debug 13,10
while car_cnt < num_cars
debug 13,10,#carw[car_cnt]//256,9,#carw[car_cnt]/256
car_cnt =car_cnt +1
wend
debug 13,10
end

sort:
sw_flag =0
car_cnt =0
while car_cnt < (num_cars -1 )
tmp= carw[car_cnt+1] ;word pointer
car_cnter= car_cnt*2 +1 ;byte pointer
if tmp.highbyte < cars[car_cnter] then
carw[car_cnt+1] = carw[car_cnt]
carw[car_cnt] =tmp
sw_flag =1
endif
car_cnt=car_cnt+1
wend
if sw_flag then goto sort
return







print out

1, 54
2 ,81
3, 25
4 ,14
5 ,6
6, 29
7 ,77
8, 32
9 ,44


5 ,6
4 ,14
3 ,25
6, 29
8, 32
9 ,44
1 ,54
7 ,77
2, 81

mombasa
- 9th May 2017, 20:11
Richard thank you very much for your time you spent for me. Your solution is complex for my knowledge. However, I will analyze it carefully. You did a lot more than I asked for. I'll let you know the developments of my work. Thanks again

towlerg
- 10th May 2017, 15:24
Setup 2 arrays, car number/name and penalty. Do a bubble sort on penalty and for each swap not swap step do the same to the car number/name array.