数组基础 | 排序算法 | 二分查找

一维数组的创建:

int[] array = {1, 2, 3};
int[] array2 = new int[]{4,5,6};

一维数组的遍历:

for (int i = 0; i < array.length; i++) {
    System.out.println(array[i]);
}

for (int i : array) {
    System.out.println(i);
}

冒泡排序算法:

 System.out.println("===========冒泡排序======================");
 array = new int[]{3, 9, -1, 10, 20};

 for (int i = 0; i < array.length - 1; i++) {
     for (int j = 0; j < array.length - i - 1; j++) {
         if (array[j] > array[j + 1]) {
             int temp = array[j];
             array[j] = array[j + 1];
             array[j + 1] = temp;
         }
     }
 }
 System.out.println(Arrays.toString(array));

选择排序算法:

System.out.println("=======选择排序==========================");
array = new int[]{3, 9, -1, 10, 20};
for (int i = 0; i < array.length; i++) {
    int minNum = array[i];
    for (int j = i + 1; j < array.length; j++) {
        if (array[j] < minNum) {
            array[i] = array[j];
            array[j] = minNum;
        }
    }
}
System.out.println(Arrays.toString(array));

二分查找算法:

 System.out.println("=======二分查找==========================");
 array = new int[]{-1, 0, 3, 5, 9, 12};
 int left = 0;
 int right = array.length - 1;
 int target = 9;
 while (left <= right){
     int middle = (left + right) / 2;
     if(array[middle] == target){
         System.out.println(target + "的位置的下标是"+ middle);
         break;
     }else if(array[middle] > target){
         right--;
     }else {
         left++;
     }
 }
 System.out.println("结束");

数组的拷贝扩容:

 int[] array = {3, 9, -1, 10, 20};
 int[] newArray = new int[5];
 //数组的拷贝
 System.arraycopy(array,0,newArray,0,array.length);
 System.out.println(Arrays.toString(newArray));
 newArray = Arrays.copyOf(array,array.length);
 //数组的扩容(扩容到原来的两倍)
 newArray = Arrays.copyOf(array,array.length * 2);
 System.out.println(Arrays.toString(newArray));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值