简体   繁体   中英

Sorting with 2D Arrays

I need help with sorting Random numbers into a 2D array. I have to generate 50 random numbers into a column of the array, then sort the numbers in order (ascending or descending). This is what I have so far and am so lost. Please Help.

UPDATED VERSION

public static void main(String[] args) 
{
    int rows = 2;
    int columns = 50;

    int[][] anArray = new int[rows][columns];

    Random rand = new Random();

    for (int i = 0; i < anArray.length; i++) 
    {
        for (int j = 0; j < anArray[0].length; j++) 
        {
            int n = rand.nextInt(100);
            anArray[i][j] = n;
        }
    }

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

    for (int i = 0; i < anArray.length; i++) 
    {
        for (int j=0;j<anArray.length-i;j++ )
        { 
            System.out.println(anArray[i][j]);
        }
    }          
}
}

You can sort 2D arrays on their initial element using a custom Comparator :

Arrays.sort(anArray, new Comparator<int[]>() {
    public int compare(int[] lhs, int[] rhs) {
        return lhs[0]-rhs[0];
    }
});

First of all, you need nested for loops in order to properly insert the random numbers into the two dimensional array. I have also updated my response to show how the sorting should be done. Hope this helps!

EDITED TO SATISFY REQUIREMENTS MENTIONED IN COMMENT BELOW.

import java.util.Arrays;
import java.util.Random;


public class Test {

/**
 * @param args
 */
public static void main(String[] args) {
    int rows = 2;
    int columns = 50;

    int[][] anArray = new int[rows][columns];

    Random rand = new Random();
    //initialize the first row only
    for (int j = 0; j < anArray[0].length; j++) 
    {
       int n = rand.nextInt(100);
       anArray[0][j] = n;
    }
    System.out.println("-----------Before the Sort----------------");
    for (int i = 0; i < anArray.length; i++) 
    {
        for (int j = 0; j < anArray[0].length; j++)
        {               
           System.out.print(anArray[i][j] + ", ");  //format any way you want
        }
        System.out.println(); //to make each row print on a new line.
    }
    anArray = mySort(anArray);
    System.out.println("-----------After the Sort----------------");
    for (int i = 0; i < anArray.length; i++) 
    {
        for (int j = 0; j < anArray[0].length; j++)
        {               
           System.out.print(anArray[i][j] + ", ");  //format any way you want
        }
        System.out.println(); //to make each row print on a new line.
    }
}

private static int[][] mySort(int[][] anArray) {
    int [][] result = new int[anArray.length][anArray[0].length];
    int thisRow[] = getRow(anArray, 0);
    Arrays.sort(thisRow);
    for(int j = 0; j < thisRow.length; j++){
        result[0][j] = anArray[0][j];
        result[1][j] = thisRow[j];
    }
    return result;
}

private static int[] getRow(int[][] anArray, int row) {
    int thisRow[] = new int[anArray[row].length];
    for(int j = 0; j < anArray[row].length; j++){
        thisRow[j] = anArray[row][j];
    }
    return thisRow;
}

}

You can sort by considering the 2D array 1D. Let's consider a 3x4 array. 1st element's index is 0, 2nd is 1, 3rd is 2, 4th is 3, 5th is 4, etc.

General formula to convert from a 1D index to a 2D:

row_index = _1D_index % nRows;
col_index = _1D_index % nCols;

For example the 5th element has the 1D index of 4, to get the row: 4 % 3 = 1, to get the col, 4 % 4 = 0, so your element is at 1,0. What's the point of all this? Now you can just make a function

int GetAt(int index)
{
    return array[index % nRows][index % nCols];
}

and something along the lines of:

void Swap(int index1, int index2)
{
   int r1 = index1 % nRows;
   int c1 = index1 % nCols;
   int r2 = index2 % nRows;
   int c2 = index2 % nCols;
   int temp = array[r1][c1];
   array[r1][c1] = array[r2][c2];
   array[r2][c2] = temp;
}

And sort the array as if it was one dimensional :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM