1.將一個給定的整型數組轉置輸出,
例如: 源數組,1 2 3 4 5 6
轉置以後的數組,6 5 4 3 2 1數組
根據題目能夠看出來,此數據排序方式是一個冒泡排序(從前日後以此肯定元素,相鄰的兩個元素比較,互換位置)實現代碼以下:spa
public class rain {
public static void main(String[] args) {
//冒泡排序
int[] a={1,2,3,4,5,6};
int t=0;
for (int i=1;i<a.length;i++){
for(int j=0;j<a.length-i;j++){
if(a[j]<a[j+1]){
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
for(int i=0;i<a.length;i++) {
System.out.println(a[i]);
}
}
}
運行結果:blog
2.如今有以下的一個數組:
int[] oldArr = {1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5} ;
要求將以上數組中值爲0的項去掉,將不爲0的值存入一個新的數組,生成的新數組爲:
int[] newArr = {1,3,4,5,6,6,5,4,7,6,7,5}排序
在這個題中使用循環的中的continue進行跳出存入新的數組:class
public class deliy {
public static void main(String[] args) {
int[] oldA = {1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5};
int j=0;
int[] newA=new int[oldA.length];
for (int i=0;i<oldA.length;i++){
if(oldA[i]==0){
//當oldArr中的值爲0是,跳出本次循環
continue;
}
//不爲0的值賦給數組newArr
newA[j]=oldA[i];
j++;//進行下一個新的數組的賦值
}
for (int k=0;k<j;k++){
//特別注意循環中K<j,你新數組存儲的值的個數是等於j的,使用newA.length,沒有賦到值會使用0進入數組中
System.out.print(newA[k]+",");
}
}
}
運行結果以下:
3.如今給出兩個數組:
數組a:"1,7,9,11,13,15,17,19"
數組b:"2,4,6,8,10"
兩個數組合併爲數組c。
實現代碼以下:
public class deliy {
public static void main(String[] args) {
int[] a={1,7,9,11,13,15,17,19};
int[] b={2,4,6,8,10};
int[] c=new int[a.length+b.length];
//複製從a的第一個開始複製,第一個數在數組中的下標爲0,寫入c,也是從第一個開始,複製長度爲a數組的長度
System.arraycopy(a,0,c,0,a.length);
//複製從b的第一個開始,但在寫入c的時候,應當從c數組的最後一個位置寫入,它最後一個位置的下邊就是數組的長度,複製長度爲b數組長度
System.arraycopy(b,0,c,a.length,b.length);
for(int i=0;i<c.length;i++){
System.out.print(c[i]+",");
}
}
}
運行結果以下: