二维不规则数组的打印
public class Test {
public static void main(String[] args) {
int data[][] = new int[][]{ //定义数组
{1,2,3,4,5},{2,4,3,2},{1}
};
//for循环
for(int x=0; x
打印数组结构
数组的冒泡排序
对一列数组进行简单的两两比较升序排列
public class SortArrayTest {
public static void main(String args[]){
int[] arr = new int[] {23,12,45,32,14,66,89,4,3};
for(int j=0; j arr[i+1]) {
int tmp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = tmp;
}
}
}
//输出数组顺序
for (int num: arr) {
System.out.print(num + " ");
}
}
}
结果
数组转置
数组转置举例:
转置前 [1,2,3,4,5,6,7,8,9]
转置后 [9,8,7,6,5,4,3,2,1]
方法一
定义一个新的数组来保存转置后的数据
public class SortArrayTest {
public static void main(String args[]){
int[] arr = new int[] {1,2,3,4,5,6,7,8,9};
int[] tmp = new int[arr.length];
for(int i=0; i<=arr.length-1;i++){
int cc = arr[i];
tmp[arr.length-1-i] = cc;
}
for (int num: tmp) {
System.out.print(num + " ");
}
}
}
方法二
在一个数组中互换首尾数据
public class SortArrayTest {
public static void main(String args[]){
int[] arr = new int[] {1,2,3,4,5,6,7,8,9};
int center = arr.length/2;
int head = 0;
int tail = arr.length-1;
for(int i=0; i<=center;i++){
int tmp;
tmp = arr[head];
arr[head] = arr[tail];
arr[tail] = tmp;
head ++;
tail --;
}
for(int num : arr){
System.out.print(num + " ");
}
}
}