Java一维数组

数组定义:
1、 int[] a = {1,2,3};
2、 int[] a = new int[]{1,2,3};
3、int[] a = new int[100];
for(int i =0;i<100;i++)
a[i]=i;

获取数组中每个元素:

①利用for循环
for(int i = 0;i<a.length;i++)
System.out.println(a[i]);

②利用for each 循环:
for(int element : a) //定义一个变量用于暂存集合中的每个元素
System.out.println(element);

③利用Arrays类的toString方法:
System.out.println(Arrays.toString(a));

数组拷贝

①Arrays类的copyOf方法
int[] brr = Arrays.copyOf(arr,arr.length);
其中第二个参数为新数组长度,可用来增加数组大小
arr = Arrays.copyOf(arr,2*arr.length)
若数组为整形,其余赋值为0;若为布尔型,赋值false;若新长度<原始长度,拷贝最前面的数组元素。

②System类的arraycopy方法
System.arraycopy(from,fromIndex,to,toIndex,count);
from:任意类型的数组
fromIndex:原始数组中待拷贝元素的起始下标
to:与from同类型数组
toIndex:目标数组放置拷贝元素的起始下标
count:拷贝元素数量

数组排序

1、直接排序

public static void selectSort(int[] arr) {
        for (int x = 0; x < arr.length - 1; x++) {
            for (int y = x + 1; y < arr.length; y++) {
                if (arr[x] > arr[y]) {
                    int temp = arr[x];
                    arr[x] = arr[y];
                    arr[y] = temp;
                }
            }
        }
    }

2、冒泡排序

public static void bubbleSort(int[] arr) {
        for(int x=0; x<arr.length-1; x++) {
             for(int y=0; y<arr.length-x-1; y++) {
                if(arr[y]>arr[y+1]){
                    int temp = arr[y];
                    arr[y] = arr[y+1];
                    arr[y+1] = temp;
                }
             }
         }
  }

public static void sort(int[] a) {
    int temp = 0;
    for (int i = a.length - 1; i > 0; --i){
      for (int j = 0; j < i; ++j){
        if (a[j + 1] < a[j]){
          temp = a[j];
          a[j] = a[j + 1];
          a[j + 1] = temp;
        }
      }
    }
  }

3、插入排序

public static void sort(int[] a) {
    int temp = 0;
    for (int i = a.length - 1; i > 0; --i){
      for (int j = 0; j < i; ++j){
        if (a[j + 1] < a[j]){
          temp = a[j];
          a[j] = a[j + 1];
          a[j + 1] = temp;
        }
      }
    }
  }

猜你喜欢

转载自blog.csdn.net/qq_43527426/article/details/83716227
今日推荐