二维数组的Java冒泡排序 [英] Bubble sort on 2D Array Java
问题描述
String[][] 2dArray = new String[counter][2];
2dArray [counter][column1] = String.valueOf(counter);
2dArray [counter][column2] = "something something something";
for(int i = 0; i < 2dArray.length-1; i++){
for(int j = i + 1; j > 0; j--){
if(2dArray[i][j] < 2dArray[i-1][j]){
int[][] temp = 2dArray[i-1][j];
2dArray[i-1][j] = 2dArray[i][j];
2dArray[i][j] = temp;
}
}
}
试图让列1上升数组进行排序。我已经研究了这里的其他参考资料和mimic'd他们,但由于某种原因,我的IDE不喜欢上面...
Attempting to sort the array so that column 1 is ascending. I've studied the other references on here and mimic'd them but for some reason my IDE does not like the above...
推荐答案
如果我理解正确,我建议如下:
If I understand you correctly, I would suggest the following:
你所需要做的是比较数组的整数
值:
What you would need to do is to compare the Integer
values of the array:
if(Integer.valueOf(2dArray[i][0]) < Integer.valueOf(2dArray[i-1][0])){
您不包括Ĵ
的原因是因为你只在第一列的值排序。 2dArray [I] [0]
让你的计数
的值,在那个特定的行。
The reason you don't include j
is because you are only sorting by the value of the first column. 2dArray[i][0]
gets you the value of your counter
at that particular row.
我也看到了一些其他的东西在你的code,可以使用固定:
I've also seen some other stuff in your code that could use fixing:
for(int i = 0; i < 2dArray.length; i++){
for(int j = i; j < 2dArray.length; j++){
if(Integer.valueOf(2dArray[j][0]) > Integer.valueOf(2dArray[j+1][0])){
String temp[] = 2dArray[j+1];
2dArray[j+1] = 2dArray[j];
2dArray[j] = temp;
}
}
}
这是更符合我认为是经典的实施冒泡的:
This is more in line with what I think is the classic implementation of BubbleSort:
private static void bubblesort(Integer[] array) {
for (int i = 0; i < array.length; i++) {
for(int j = 0; j < array.length - 1; j++) {
if(array[j].compareTo(array[j+1]) > 0) {
swap(j, j+1, array);
}
}
}
}
private static void swap(Integer index1, Integer index2, Integer[] array) {
if(index1 == index2)return;
Integer temp = new Integer(array[index2]);
array[index2] = array[index1];
array[index1] = temp;
}
除了在你的情况,我是治疗你的数组作为一维的,因为你只有一个维度排序。
Except in your case, I'm treating your array as a one-dimensional, since you are only sorting by one dimension.
这篇关于二维数组的Java冒泡排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!