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?
2 answers
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 ()