Given a two-dimensional java-array, where the first line contains letters of the Latin alphabet in lower case, while they can be repeated. Need to sort the columns in the array so that the first elements of each column are sorted alphabetically from a to z?

  • The columns themselves should not change, only their location in the array changes - Artem Gafarov

2 answers 2

The implementation of the sort function:

 private static void sort(char[][] arrayIn, int start, int end) { //массив, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ Π±ΡƒΠ΄Π΅ΠΌ ΡΠΎΡ€Ρ‚ΠΈΡ€ΠΎΠ²Π°Ρ‚ΡŒ char array[] = arrayIn[0]; if (start >= end) return; int i = start, j = end; int cur = i - (i - j) / 2; while (i < j) { while (((int)array[i] <= (int)array[cur]) && i < cur) { i++; } while (((int)array[j] >= (int)array[cur]) && j > cur) { j--; } if (i < j) { //мСняСм столбцы i ΠΈ j мСстами swap(arrayIn, i, j); //вносим измСнСния Π² массив, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ сортируСм array = arrayIn[0]; if (i == cur) { cur = j; } else if (j == cur) { cur = i; } } } sort(arrayIn, start, cur); sort(arrayIn, cur + 1, end); } private static void swap(char[][] array, int i, int j) { // ΠŸΠ΅Ρ€Π΅ΠΌΠ΅Ρ‰Π°Π΅ΠΌ столбцы for (int k = 0; k < array.length; k++) { char buff = array[k][i]; array[k][i] = array[k][j]; array[k][j] = buff; } } 

An example call for the array char[][] arr :

  char[][] arr = { {'b', 'f', 'g', 'a', 'z', 'o'}, {'1', '2', '3', '4', '5', '6'}, {'1', '2', '3', '4', '5', '6'}, {'1', '2', '3', '4', '5', '6'}, {'1', '2', '3', '4', '5', '6'} }; sort(arr, 0, arr.length); for (char[] anArr : arr) { for (char anAnArr : anArr) { System.out.print(anAnArr + " "); } System.out.println(); } 

Conclusion:

 abfgoz 4 1 2 3 6 5 4 1 2 3 6 5 4 1 2 3 6 5 4 1 2 3 6 5 

    To do this, it is enough to use one of the known sorting algorithms, for example, quick sorting. At the same time, you need to implement it manually, since you will have to change the swap () method, in which you now need to change the array columns (since changing the columns in the array is not very convenient, you can change the column index of this element with the row index. When output this should also be taken into account). Or create a class that stores a two-dimensional array, in which the comparison method is redefined:

     class ArrayContainer implements Comparable<ArrayContainer>{ public char[] data; @Override public int compareTo(ArrayContainer other){ return ((Character)data[0]).compareTo((Character)other.data[0]); } } 

    Next, an ArrayContainer array is created, sorted using one of the available sorting methods, for example, Arrays.sort ()