Java的复制数组、排序以及插入数组(上课笔记版)

大家先体验一下Java的简单性。

1.复制数组

import java.util.Arrays;
/*** 复制数组
 * 有一个数组int one长度为5,在使用过程中,数组满了。但还要往one中存数据。
 * 要复制数组
 */
public class Test {
    public static void main(String[] args) {
        int[] one = {1, 2, 3, 4,5};
        // Arrays 用于操作数组的工具类
        int[] oneCopy = Arrays.copyOf(one, one.length * 2);
        for (int temp : oneCopy) {
            System.out.println(temp);
        }
    }
}
public class Test {
    public static void main(String[] args){
        /**
         * 复制数组
         * 有一个数组int one长度为5,在使用过程中,数组满了。但还要往one中存数据。
         * 要复制数组
         */
        int[] one = {1,2,3,4,5};
        //先创建一个新数组,长度为one*2
        int[] oneCopy = new int[one.length*2];
        //得循环旧数组长度,因为新的长度比旧的长,会导致数组越界
        for(int i=0;i<one.length;i++){
            oneCopy[i] = one[i];
        }
        //打印
        for(int temp:oneCopy){
            System.out.println(temp);
        }
    }
}

下面是用以前学的C的思想写的

2.排序

import java.util.Arrays;
public class Test {
    public static void main(String[] args) {
        int[] one = {89, 6, 1, 76, 4, 12, 5, 22, 35, 36, 0};
        // 在Java中如何排序?
        Arrays.sort(one);
        for (int temp : one) {
            System.out.print(temp + ",");
        }
    }
}

同样下面用C的写法写一下

//冒泡排序
public class Test {
    public static void main(String[] args) {
        int[] one = {1,2,4,6,3,5,0};
        int n = one.length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - 1 - i; j++) {
                if (one[j] > one[j + 1]) {
                    int t = one[j];
                    one[j]=one[j+1];
                    one[j+1]=t;
                }
            }
        }
        for (int i = 0; i < n; i++) {
            System.out.print(one[i]+" ");
        }
    }
}
//插入排序
public class Test {
    public static void main(String[] args) {
        int[] one = {1,2,4,6,3,5,0};
        for (int i = 1; i < one.length; i++) {
            int n = one[i];
            int j = i - 1;
            while (j >= 0 && one[j] > n) {
                one[j + 1] = one[j];
                j = j - 1;
            }
            one[j + 1] = n;
        }
        for (int temp : one) {
            System.out.print(temp+" ");
        }
    }
}

插入数组

import java.util.Arrays;

/**
 * 查找元素
 */
public class Test {
    public static void main(String[] args) {
        int[] one = {1,2,4,6,3,5,0};
        // Java中查找元素分为两步:
        // 第一步:排序:
        Arrays.sort(one);
        // 第二步:查找 num是排序后的下标
        int num = Arrays.binarySearch(one, 2);
        System.out.println("下标是:" + num);
        System.out.println(one[num]);
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值