1

i have an 2d Array which is [2][10]. It is filled with random numbers. Could someone please help me how to sort it? I dont know why but any found way to sort it with Comparator doesnt work for me. So im trying to do that in a loop. It has to be sorted by the column.

Im trying to play with creating a temporary array and inserting the value into it, but i dont know how to compare values: [0][0] and [0][1]. My try is do 2 for loops and inside it:

for (int i = 0; i < arr4.length; i++) {
    for(int j = 0; j < arr4[i].length; j++) {
        if(arr4[i][j] > ???????)
    temparray = arr4[i][j];
    }
 }

Help me please...

2
  • 2
    Please provide sample test case and expected output for that test case. Commented Oct 1, 2020 at 15:57
  • 2
    Do you want to sort by row order or column order? Commented Oct 1, 2020 at 15:57

1 Answer 1

1

if you need to sort line by line you need to update your solution like this

  for (int i = 0; i < arr4.length; i++) {
        for(int j = 0; j < arr4[i].length-1; j++) {
            if(arr4[i][j] > arr4[i][j+1]){
              temparray = arr4[i][j];
              arr4[i][j] = arr4[i][j+1]
              arr4[i][j+1] = temparray  ;
              j=0;
          }
        }
     }


input:
[1.0, 2.0]
[6.0, 4.0]
[5.0, 4.0]

output:

[1.0, 2.0]
[4.0, 6.0]
[4.0, 5.0]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.