Shop OBEX P1 Docs P2 Docs Learn Events
Sorting Signed Numbers — Parallax Forums

Sorting Signed Numbers

ATSATS Posts: 4
edited 2011-05-10 15:05 in BASIC Stamp
I need to sort an array of signed integers in ascending order. After attempting to do a simple bubble sort, I get this result:
38
44
81
118
-94
-81
-50
-44
-7
Based upon this result, I know I need to first check somehow to see if the integers being sorted are negative and do something if they are... How can I resolve this problem? Check out my attached sort routine code. Thanks.

Comments

  • Phil Pilgrim (PhiPi)Phil Pilgrim (PhiPi) Posts: 23,514
    edited 2011-05-10 07:43
    When comparing two numbers, check first to see if they have different sign bits. If so, the one with the sign bit set is the smaller of the two; if not, just do a normal comparison.

    -Phil
  • Mike GreenMike Green Posts: 23,101
    edited 2011-05-10 07:47
    Although PBasic has some provisions for handling signed values, it really handles 16 bit values as unsigned integers in the range of 0 to 65535. Some arithmetic operations work with unsigned integers and with signed integers in the range -32768 to 32767 (like + and -), but some operations don't work (like * and / as well as comparisons).

    If you want to do a signed compare, you first need to look at the sign bits. If they're both positive or both negative, you can compare them directly. If the signs are opposite, you only need to compare the signs since (-) < (+)
  • ATSATS Posts: 4
    edited 2011-05-10 09:31
    Can you please provide an example for comparing the signs? Thanks so much to both of you!
  • Mike GreenMike Green Posts: 23,101
    edited 2011-05-10 10:06
    IF value1.BIT15 = value2.BIT15 THEN

    Read the chapter in the Stamp Manual on memory allocation for further discussion of this technique.
  • vaclav_salvaclav_sal Posts: 451
    edited 2011-05-10 11:47
    Unless your sort routines (ascending and descending) are an exercise for learning purpose I hope you do realize that once you process one order you also have done the other one if you reverse the indexing of the result.
  • Tracy AllenTracy Allen Posts: 6,662
    edited 2011-05-10 15:05
    Another way is to first add 32768 to all the numbers, then sort them, then subtract 32768. That "rotates" the number line so that all are positive for the sort.
Sign In or Register to comment.