2 dimesnional array - sorting single row?
BlitzMax Forums/BlitzMax Programming/2 dimesnional array - sorting single row?
| ||
I have a 2 dimensional array which I fill with random numbers. How do I sort each row of numbers in the array in ascending order? e.g here's my array data: 4 10 1 50 33 44 78 20 27 69 11 how would I just sort each row idependently? |
| ||
Maybe look at bubble sort algorithms. they're not the most efficient but it'll give you a basic understanding of how these things are done. Cheers Charlie |
| ||
use array of arrays:Strict Local arr:Int[][] 'arr[2][6] arr = arr[..2] For Local i = 0 Until Len(arr) arr[i] = arr[i][..6] Next For Local y = 0 To 1 For Local x = 0 To 5 arr[y][x] = Rand(0 , 1000) Next Next Print "--- --- ---" For Local y = 0 To 1 print For Local x = 0 To 5 Print "arr["+y+","+x+"]="+arr[y][x] Next Next arr[0].Sort 'sort ascending arr[1].sort False 'sort descending Print "--- --- ---" For Local y = 0 To 1 print For Local x = 0 To 5 Print "arr["+y+","+x+"]="+arr[y][x] Next Next |
| ||
Hm are you asking how to sort in general, or you can sort but having trouble with a 2d array? 1. Quicksort is considerably more efficient than bubble sort, and yet not that much harder, so I suggest you use it instead. 2. I doubt this will be the smartest solution, but it should work: Local array2d:Int[2, 10] Local row1:Int[10] Local row2:Int[10] For Local i:Int = 0 Until 10 row1[i] = array2d[0, i] row2[i] = array2d[1, i] Next sort(row1) sort(row2) For Local i:Int = 0 Until 10 array2d[0, i] = row1[i] array2d[1, i] = row2[i] Next Function sort(array:Int[]) 'go nuts End Function |
| ||
You would need to write your own sort function. Here is an example Two problems with this is that it only takes a 2 dimensional array, and it uses bubble sort which is a slow way to sort long arrays. You could also use array of arrays This has the advantage of not needing to write your own function as well as being usable on all sorts of dimensions. The disadvantage is the need to initialize each dimension of the array individually. |
| ||
Perfect! Thanks all. :) |
| ||
@Zeke: Thanks man! I didn't know you could use slices in that way (Had tried and couldn't get it to work eons ago...). Would be cool if the Sort function of arrays was updated to allow choosing which dimension to sort. Then again, these code snippets are fine and I loathe bloat... Russell |