2 dimesnional array - sorting single row?

BlitzMax Forums/BlitzMax Programming/2 dimesnional array - sorting single row?

Amon(Posted 2009) [#1]
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?


jkrankie(Posted 2009) [#2]
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


Zeke(Posted 2009) [#3]
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



Czar Flavius(Posted 2009) [#4]
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



TomToad(Posted 2009) [#5]
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.


Amon(Posted 2009) [#6]
Perfect! Thanks all. :)


Russell(Posted 2009) [#7]
@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