1

Need your expert guidance as how to sort a 2D array, row-wise ( means considering each row independently and sort all rows independently of a 2D array) in Visual Studio C#.Example

First row: 5 4 3 6 Second row: 2 3 1 4

Sorted: First row :3 4 5 6 Second row: 1 2 3 4

There is a method called Array.Sort (), but it is specific to 1D arrays only. Thanks and Regards Asad

2 Answers 2

1

If your 2D array is a jagged array like:

int[][] foo = new int[][] { 
    new int[] { 5, 4, 3, 6 }, 
    new int[] { 2, 3, 1, 4 } };

you can do it by using LINQ:

for (int i = 0; i < foo.Length; i++)
    foo[i] = foo[i].OrderBy(s => s).ToArray();
Sign up to request clarification or add additional context in comments.

Comments

0

Your example is of a 1D array, by 2D array do you mean somthing lke

int[2,2] foo;

so you'll do some thing like.

foo[0,0] = 0;
foo[0,1] = 1;
foo[1,0] = 1;
foo[1,1] = 1;

please clarify.

2 Comments

Actually I have a 2D array of 10x10 elements. Each of the 10 row contains 10 elements. I want to sort each row of this 2D array independent of the other row.
in that case it would be better for you to have a List of arrays. That way you can loop through them and sort each array. Beter still have a List<> of SortedLists.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.