我想在e bidimensionnal数组(升序)中订购一列,但在结尾处保留所有0。 例如:
input = {5,2,1,0,4}
output = {1,2,4,5,0}
我已经完成了这个命令数字(升序)的方法,但我还没有找到如何将0保持在最后。 (可以有多个0)
public static void orderCol(int[][] tab, int iCol){ // This will order numbers in the column i (ascending AND placing 0 at the end) (In case the user didnt already do it in the input file this will prevent further problems).
int temp;
for(int i=0; i< tab[0].length-1;i++){
if(tab[iCol][i+1] < tab[iCol][i]){
//swapping
temp = tab[iCol][i];
tab[iCol][i] = tab[iCol][i+1];
tab[iCol][i+1] = temp;
i=-1;
}
}
}
希望你能提前帮助,谢谢!
答案 0 :(得分:0)
你可以先计算你的数组有多少0,然后创建一个只有非0的新数组,然后对非0进行排序并附加0的
public int[] orderCol(int[][] tab, int iCol){ // This will order numbers in the column i (ascending AND placing 0 at the end) (In case the user didnt already do it in the input file this will prevent further problems).
int index = 0;
int[] newArray = new int[tab[0].length];
for (int x: tab[0]) { // iterates each element on tab[0]
if (x != 0) newArray[index++] = x;
}
// SORT YOUR newArray HERE using any sort algo
while(index != tab[0].length) newArray[index++] = 0;
return newArray;
}