0

I'm stuck on an assignment where I'm supposed to use helper methods to sort rows and columns in a 2D int array in Java. It's explicitly required to use two different methods to sort an array. Anyways so here is my code for sorting a row

public static void sortOneRow(int[] arr1) {

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

And here's to sort a column if given an input parameter representing the 2D array and the column index:

  public static void sortOneColumn(int[][] x, int colNo) {
    // Sorting one column
    int[] thisCol = new int[x.length];
    for (int i = 0; i < x.length; i++) {
        thisCol[i] = x[i][colNo];
    }

    // Sort 

    sortOneRow(thisCol);
    for (int i = 0; i < x.length; i++) {
        x[i][colNo] = thisCol[i];
    }

Now, how do I call these two methods in another method that only takes in the 2D Array and I have to first sort rows then sort columns?

4
  • 1
    Why istn't your sortOneRow equivalent to the sortOneColumn one? In both cases it is a 2D array right? Commented Mar 27, 2018 at 0:33
  • Cant you use Arrays.sort method as well? Commented Mar 27, 2018 at 0:46
  • @Adya no, can't use that Commented Mar 29, 2018 at 1:27
  • @JorgeCampos by the instructions I have to create different methods to sort rows and columns then use each of those methods to sort a 2D matrix Commented Mar 29, 2018 at 1:28

1 Answer 1

1

If i understand correctly, you want to reuse your own methods to sort an 2D array. Hope this can help:

public static void sort(int[][] a){
   if(a == null || a.length == 0) return;

   for(int row = 0; row < a.length; row++) {
     sortOneRow(a[row]);
   }

   for(int col = 0; col < a[0].length; col++) {
     sortOneColumneRow(a, col);
   }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, this is perfect. Thanks!
@samdukez thanks, if so, could you plz kindly accept my answer to mark that your question has been resolved :) thanks
hey sorry I'm on a new account and I tried to accept the answer but it tells me I need 15 reputation points.

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.