George
George

Reputation: 5

Sorting 2D array of Int in Swift

I'm trying to sort array like this one [[Int]] of 6 rows and 6 columns with sorted(by: { $0[0] < $1[0] }). But sorted array is sorted only by the first number in a row! This is example source array:

5;8;1;13;2;6

20;8;19;12;41;13

23;14;15;36;7;18

9;27;21;12;3;44

25;16;7;18;9;30

1;32;13;34;25;45

And this is what I've got after sorting:

1;32;13;34;25;45

5;8;1;13;2;6

9;27;21;12;3;44

20;8;19;12;41;13

23;14;15;36;7;18

25;16;7;18;9;30

I don't need row's order to be changed. I need to get something like that:

1;2;5;6;8;13

8;12;13;19;20;41

7;14;15;18;23;36

3;9;12;21;27;44

7;9;16;18;25;30

1;13;25;32;34;45

Here is my sample output. I will be grateful for any help!

Upvotes: 0

Views: 114

Answers (1)

vadian
vadian

Reputation: 285190

Due to value semantics you have to map the array to its sorted content

let array = [[5,8,1,13,2,6],
             [20,8,19,12,41,13],
             [23,14,15,36,7,18],
             [9,27,21,12,3,44],
             [25,16,7,18,9,30],
             [1,32,13,34,25,45]]

let sortedArray = array.map{ $0.sorted() }
print(sortedArray)

Upvotes: 1

Related Questions