I'd do this in the following type manner, personally, as I find it to be more intuitive to my own style personally:
Code: (Select All)
Dim d(-10 To 10)
For i = -10 To 10
d(i) = i
Print d(i), 'print the jumbled up order
Next
Print
'sort
Dim newLow(0 To 21)
Dim newHigh(0 To 21)
For i = -10 To 10 'seperte lows from highs
Select Case Sgn(d(i))
Case -1
newlow = newlow + 1
newLow(newlow) = d(i)
Case 1
newhigh = newhigh + 1
newHigh(newhigh) = d(i)
Case 0: zero = zero + 1
End Select
Next
BubbleSortAbs newLow(), newlow 'sort the lows
BubbleSortAbs newHigh(), newhigh 'sort the highs
count = -10
For i = 1 To newlow 'rebuild with the lows
d(count) = newLow(i)
count = count + 1
Next
For i = 1 To zero 'rebuild with the 0s
d(count) = 0
count = count + 1
Next
For i = 1 To newhigh 'rebuild with the 0s
d(count) = newHigh(i)
count = count + 1
Next
For i = -10 To 10
Print d(i), 'print the sorted order
Next
Print
Sub BubbleSortAbs (a(), finish) 'sort by ABS value
For i = 1 To finish
For j = i + 1 To finish
If Abs(a(i)) > Abs(a(j)) Then Swap a(i), a(j)
Next
Next
End Sub
This is as simple as can be.
First we make our data array.
Then we scan it and make two new data arrays -- one for negative values, one for positive values.
Then we sort those two arrays by ABS value so they're in the order we want.
And finally we just put those two arrays back together into a single sorted array in the proper order.
Luke mentioned a speed penalty... I... I honestly think this might be *FASTER* than a regular bubble sort would be, in many cases.
LOL -- and I'm *NOT* crazy to say that!!
Bubblesorts are notoriously inefficient. The bigger the array size to sort, the worse they become. In this case, we're cutting our array sizes in half (assumingly, since the data in this case is perfectly balanced in negative and positive values). I would imagine that with large amounts of data, such as 1,000,000 entries, this would be faster than a plain bubblesort.
After all, this would do 2 * 500,000 bubblesorts, whereas a plain bubblesort would do 1,000,000 sorts.
Of course, if you're using Bubblesort on such large arrays of data, speed probably isn't your primary concern to start with. I just thought I'd mention mention the difference in outcomes in this case. Luke is worried his might cause some performance hit. On the other hand, with the sorting I'm doing, this will probably be a performance BOOST.
And that's the beauty and oddity of programming!