user3213110
user3213110

Reputation: 199

Java: How to sort part of a 3d array?

I have this array: array[2][7][2].

for (int i = 0; i < 2; i++) {
    for (int j = 0; j < 7; j++) {
        syso(array[i][j][0] + " ");
    }
    syso("/n");
}

Currently the above code prints out:

4 1 2 5 9 0 1

2 3 1 9 9 3 1

Is there a way to have these sorted somehow? I don't really care about array[i][j][1], only about array[i][j][0].

I wrote myself a QuickSort function but obviously this random piece of code doesn't work:

for (int i = 0; i < array.length; i++) {
    quickSort(array[i][0], 0, array[i].length - 1);     
}

EDIT:

Here's my QuickSort function as well:

static int partition(int a[], int l, int r) {
    int pivot = a[r];
    int k=l-1;

    for(int i=l; i <= r; i++) {
        if (a[i] <= pivot) {
            k++;

            int w = a[i];
            a[i] = a[k];
            a[k] = w;
        }
    }
    return k;
}

static void quickSort(int [] a, int l, int r) {
    if (l>=r) {
        return ;
    }

    int k = partition(a, l, r);
    quickSort(a, l, k-1);
    quickSort(a, k+1, r);
}

Upvotes: 0

Views: 353

Answers (1)

Alex Salauyou
Alex Salauyou

Reputation: 14348

int[][] another = int[2][7];
for (int i = 0; i < array.length; i++) {
   for (int j = 0; j < array.length; j++) {
      anotner[i][j] = array[i][j][0];
   }
}
for (int[] a : anotner) {
    Arrays.sort(a);
}

then print anotner as you do using syso().

Upvotes: 1

Related Questions