public class Arrays {
public static void main(String[] args) {
int arrays[] = {1,2,3,4,5,6};
int[] reverse = reverse(arrays);
printArrays(reverse);//6 5 4 3 2 1
}
//反转数组
public static int[]reverse(int[] arrays){
int[] result = new int[arrays.length];
//反转操作
for(int i=0,j=arrays.length-1;i<arrays.length;i++,j--){
result[i]=arrays[j];
}
return result;
}
//利用增强for循环打印数组
public static void printArrays(int []arrays){
for (int array:arrays){
System.out.print(array+" ");
}
}
}
二维数组的打印
public class MoreArray {
public static void main(String[] args) {
int arrays[][]={{1,2},{3,4},{5,6},{9,8}};
for (int i=0;i<arrays.length;i++){
for (int j=0;j<arrays[i].length;j++){
System.out.println(arrays[i][j]);
}
}
}
}
冒泡排序
flag是为了减少比较次数,因为有些已经排好序了,不需要比较了
public class Sort {
public static void main(String[] args) {
int[]array={1,5,99,3,22,6};
int[] sort = sort(array);
System.out.println(Arrays.toString(sort));
}
public static int[] sort(int[]arrays){
int temp;
for (int i=0;i<arrays.length-1;i++){
boolean flag=false;//通过flag标识减少没有意义的比较
for(int j=0;j<arrays.length-1-i;j++){
if(arrays[j+1]>arrays[j]){
temp = arrays[j+1];
arrays[j+1] = arrays[j];
arrays[j] = temp;
flag = true;
}
}
if(flag==false){
break;
}
}
return arrays;
}
}