我正在尝试在2D数组上实现冒泡排序以按行升序排列,但它只移动第一个项目。我怎样才能解决这个问题?
for(int i = 0; i<differencearray.length; i++){
for(int j = 0; j<differencearray[i].length-1; j++){
if(differencearray[i][j]>differencearray[i][j+1]){
int temp = differencearray[i][j];
differencearray[i][j] = differencearray[i][j+1];
differencearray[i][j+1] = temp;
}
}
}
输入是:
2147483647 15 9 13 24
15 2147483647 18 16 17
9 18 2147483647 12 27
13 16 12 2147483647 25
24 17 27 25 2147483647
输出结果为:
15 9 13 24 2147483647
15 18 16 17 2147483647
9 18 12 27 2147483647
13 12 16 25 2147483647
17 24 25 27 2147483647
任何帮助都会很棒!
答案 0 :(得分:2)
冒泡排序是O(n^2)
算法,因此单个数组需要2个for循环。
如果你有n个数组,那么你需要3个for循环才能对所有行进行排序。
这使得它成为O(n^2*m)
算法。 (其中m是行数)
... SOOOO
for(int i = 0; i < rowCount; i++){
for(int j = 0; j < colCount; j++){
for(int k = 0; k < colCount; k++){
if(differencearray[i][k]>differencearray[i][k+1]){
int temp = differencearray[i][k];
differencearray[i][k] = differencearray[i][k+1];
differencearray[i][k+1] = temp;
}
}
}
}
答案 1 :(得分:0)
我本人对此有点困惑...
我注意到的最大区别是您的气泡排序仅循环访问矩阵一次。它需要保持交换元素,直到所有内容都已排序。要解决此问题,您需要一个适当的退出条件(一旦没有可用交换的条件,它需要继续进行迭代)。因此,它有助于添加带有布尔表达式的while循环。
这里的转折点是 if ,您的if语句的计算结果为false(没有数字可交换),而while循环将结束程序。否则,程序将继续重新循环直到满足while条件。最后,您将获得一个正确排序的矩阵。
int differencearray[][] = {{2147483647, 15, 9, 13, 24},
{15, 2147483647, 18, 16, 17},
{9, 18, 2147483647, 12, 27},
{13, 16, 12, 2147483647, 25},
{17, 24, 25, 27, 2147483647}};
int temp;
// initializing a boolean
boolean unsorted = true;
while(unsorted == true) {
// exit condition to break while
unsorted = false;
// row
for(int i = 0; i < differencearray.length; i++) {
// column
for(int j = 0; j < differencearray.length - 1; j++) {
// swapping values
if(differencearray[i][j] > differencearray[i][j + 1]) {
// keeps re-entering while if unsorted remains true
unsorted = true;
temp = differencearray[i][j + 1];
differencearray[i][j + 1] = differencearray[i][j];
differencearray[i][j] = temp;
}
System.out.println("INSIDE " + Arrays.deepToString(differencearray));
}
}
System.out.println("OUTSIDE " + Arrays.deepToString(differencearray));
}
答案 2 :(得分:0)
这段代码生成了一个 2D int 随机数数组,范围在 0 到 10 之间。很高兴收到您的评论。
private TableLayout createTableLayout() {
tableLayout = (TableLayout) mDialogLayout.findComponentById(ResourceTable.Id_md_table_layout);
ComponentContainer.LayoutConfig layoutConfig = new ComponentContainer.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_CONTENT,
ComponentContainer.LayoutConfig.MATCH_CONTENT);
tableLayout.setRowCount(getRowCount());
tableLayout.setColumnCount(getColumnCount());
tableLayout.verifyLayoutConfig(layoutConfig);
for (int position = 0; position < getCount(); position++) {
CircleView cv = new CircleView(mContext);
cv.setLayoutConfig(cvlayoutConfig);
tableLayout.addComponent(cv);
}
return tableLayout;
}