gpt4 book ai didi

java - 在java中使用BUBBLE SORT对二维字符串数组进行排序

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:31:32 26 4
gpt4 key购买 nike

有人问过类似的问题,但从来没有问过二维字符串数组,因此在尝试了很长时间后我找不到我想要的。我正在尝试使用 BubbleSort 在 Java 中对二维字符串数组进行排序。

作为输入,我收到一个二维字符串数组(一个表)和您应该排序的“列”的索引。我应该按指定列中的值对行进行排序。

可以看到第一个索引是行索引,第二个索引是列索引。例如下面的Java数组和表一一对应:

String[][] table = {
{"a", "b"},
{"c", "d"}
};

-

0   1
+---+---+
0 | a | b |
+---+---+
1 | c | d |
+---+---+

继续这个例子,table[0][1] 将产生值“b”,因为它是第 0 行和第 1 列中的项目。

重要提示:我不允许使用 Java 库中的任何排序算法,例如 Arrays.sort。

这是我到目前为止尝试过的:

class Solution {
public static void stableSort(String[][] table, int column) {
int i;
int j;
String temp = null;
for (i = 0; i < table.length - 1; i++) {
for (j = 0; j < table.length - 1 - i; j++) {
if (table[i][j].compareTo(table[i][j + 1]) > 0) {
temp = table[i][j];
table[i][j] = table[i][j + 1];
table[i][j + 1] = temp;
}
}
}
}
}

我得到一个索引超出范围的错误,而且它也没有工作,因为测试期望表 [0][0] 中的结果不同感谢您的帮助。

最佳答案

public static String[][] stableSort(String[][] table, int column) {
int i=0,j=0;
String[] temp = null;
boolean swap=true;
while(swap)
for (i = 0; i < table.length - 1; i++) {
swap=false;
if(table[i][column].compareTo(table[i+1][column]) > 0){
temp = table[i];
table[i] = table[i+1];
table[i+1]=temp;
swap=true;
}
}
return table;
}

它一直应用冒泡排序,直到不再执行交换。此时,while(swap) 条件不再满足,方法返回。在 main 中尝试过并且有效(如果我理解你的意思):

public static void main(String[] args) {
String[][] table = {
{"z", "b", "v"},
{"s", "w", "a"},
{"r", "c", "h"}
};

table = stableSort(table,1);
for(int i = 0; i < table.length; i++){
for(int j = 0; j < table[0].length; j++){
System.out.printf("%5s ", table[i][j]);
}
System.out.println();
}
}

这个输出:

z     b     v 
r c h
s w a

关于java - 在java中使用BUBBLE SORT对二维字符串数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54202971/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com