数组---(一维、二维数组,求最值,排序)

来源:互联网 发布:linux修改字符集为gbk 编辑:程序博客网 时间:2024/05/16 19:41

数组(引用类型):
1 数组 :

存储一组相同数据类型的数据结构数组本身是引用类型,存储在堆中。数组可以存储任意类型:基本类型、引用类型。double[] d = new double[10]; 用于存储10个double类型的数据Person[] p = new Person[3];  用于存储3个Person类型的对象 对象数组要想使用数组,必须先创建,再开辟空间。创建时需要指明数组的大小,并且大小一旦确定,不能更改,但是数组中的元素的值是可以改变的。

2 声明以及创建

动态声明:    数据类型[] 数组名 = new 数据类型[长度];静态声明:       数据类型[] 数组名 = {值,值,值,。。。。};数据类型[] 数组名 = new 数据类型[]{值,值,值,。。。。};

3 数组的长度:

length属性

4 数组的使用:

通过下标访问数组的元素[0,length-1]

5 遍历数组

通过循环控制数组for(int i=0;i<arr.length;i++){    arr[i]}通过for增强版遍历数组:优点 遍历方便  缺点  没有下标for(int i : arr){    i}

6.产生随机数:

int r = (int)(Math.random()*(大数-小数+1)+小数);//(Math.random()产生0~1的值eg:如果产生1-100的随机数int r = (int)(Math.random()*(100-1+1)+1);

7.对象数组:

类名 [] 数组名 = new 类名[数组长度];给对象数组赋值:    数组名[数组下标] = new 类名();例子:学生对象的数组    Student[] arr = new Student[5];    arr[1] = new Student("李四", 22, '女');    

8.获取数组最值:

获取最大值:    方式1:        思路:获取最值需要进行比较,每一次比较都会有一个较大的值,因为该值不确定,通过一个变量进行存储;            让数组中每一个元素都和这个变量进行比较,如果大于变量的值,就用该变量记录较大值;            当左右的元素都比较完成,那么该变量中存储的就是数组的最大值了        步骤:定义变量。初始化值为数组任意一个元素即可;            通过循环语句对数组进行遍历            在遍历过程中定义判断条件,如果遍历到的元素比变量中的元素大,就赋值给该变量
class Demo{     public static void main(String[] args) {            ArrayDemo array = new ArrayDemo();            int score[] ={55,66,77,88,99};            // 求成绩之和            int sum = getSum(score);            System.out.println("成绩之和为:" + sum);            // 平均成绩            double avg = getAvg(score);            System.out.println("平均成绩为:" + avg);            // 最大值            int max = getMax(score);            System.out.println("最大值为:" + max);            // 最小值            int minIndex = getMin(score);            int min = score[minIndex];            System.out.println("最小值为:" + min);        }    public static int getSum(int[] a) {            int sum = 0;            for (int i = 0; i < a.length; i++) {                sum = sum + a[i];            }            return sum;        }        public static double getAvg(int[] a) {            int sum = getSum(a);            double avg = (sum + 0.0) / a.length;            return avg;        }        public static int getMax(int[] a) {            int max = a[0];// 将第一位数作为最大值            for (int i = 1; i < a.length; i++) {                if (a[i] > max) {                    max = a[i];                }            }            return max;        }        public static int getMin(int a[]) {            int minIndex = 0;// 假设数组下标为0的时候为最小是            for (int i = 1; i < a.length; i++) {                if (a[i] < a[minIndex]) {                    minIndex = i;                }            }            return minIndex;        }    }   

注意:

编译只检查语法错误,运行会检查值是否正确    例子:int[] x = new int[3];        System.out.println(x[30]);//编译无错误,运行数组越界异常(ArrayIndexOutOfBoundsException)        int[] arr = new int[3];        arr=null;        System.out.println(arr[1]);//NullPointerException;空指针异常,当引用没有任何指向,为null的时候,该引用还在操作实体    例子:        int[] x = new int[3];        int [] y =x;//y与x指向同一地址        y[1] = 89;//当y1等于89时候,x1也等于89        x = null;//当x等于null呢,地址不在指向堆中,没有垃圾在堆中。

数组排序:

冒泡排序:依次比较相邻的数据,将小的数据放在前面,大的放在后面    思路:        比较相邻的两个数,会进行n-1轮的比较,每一轮会比较n-1-i次之后,将数组中最大的排在最后选择排序:在第一轮遍历N个数据,找出最小值与第一个元素进行交换           在第二轮遍历剩下的N-1个数,找出最小的与第二个元素进行交换       .....       在第N-1轮遍历剩下2个数,找出最小的和第N-1个进行交换      思路:每一轮从待排序的记录中选出最小的元素,顺序的放在已经排好的序列的后面,      直到全部数据排序完毕。      注意:        为了减少交换的次数,在每一轮中记录最小元素的索引,在此轮比较结束后交换,提高效率插入排序:将一个新的数据放入到一个有序的序列中,并保持原有的顺序    思路:从数组的第一个元素a[0]开始,将其后一个元素a[1]插入到a[0]的前或者后,接着继续该过程,    每次都将a[i]插入到已经排序好的a[0]~~a[i-1]之中合适的位置,保证原有的序列不变    注意:从第二个位置开始,依次取出元素与前面有序的序列进行比较,插入合适的位置。相对于其他排序,效率比较高。查找:    顺序查找:如果存在,返回对应的索引值,如果不存在,返回-1    二分法查找:折半查找  前提:数组是有序的(升序)    从数组的中间开始查找,如果中间的数大于要找的对象,则在左边找    如果中间的数小于要查找的元素,在右边找    如果相等,直接返回下标 

Demo:

import java.util.Arrays;    /**     * 工具类----都为static修饰的     *      */    public class ArraryUtil {        // 冒泡排序        public static void bubbleSort(int nums[]) {            for (int i = 0; i < nums.length - 1; i++) {                for (int j = 0; j < nums.length - 1 - i; j++) {                    if (nums[j] > nums[j + 1]) {                        // 交换                        swap(nums, j, j + 1);                    }                }            }        }        // 选择排序        public static void chooseSort(int nums[]) {            for (int i = 0; i < nums.length; i++) {                // 最小值的下标。初始化为基准值的下标                int minIndex = i;                for (int j = i + 1; j < nums.length; j++) {                    if (nums[minIndex] > nums[j]) {                        minIndex = j;                    }                }                // 循环结束:已经找到了本轮最小值的下标                if (minIndex != i) {                    swap(nums, minIndex, i);                }            }        }        // 选择排序2        public static void chooseSort2(int nums[]) {            for (int i = 0; i < nums.length; i++) {                for (int j = i + 1; j < nums.length; j++) {                    if (nums[i] > nums[j]) {// 确保最左边的元素是最小的                        swap(nums, i, j);                    }                }            }        }        // 插入排序        public static void insertSort(int nums[]) {            for (int i = 1; i < nums.length; i++) {// 外层循环控制循环次数                for (int j = i; j > 0; j--) {                    if (nums[j] < nums[j - 1]) {// 左边是有序的,当前值比左边值大不用交换                        swap(nums, j, j - 1);                    } else {                        break;                    }                }            }        }        // 顺序查找:如果找到返回索引值,如果没找到返回-1        public static int sort(int nums[], int num) {            for (int i = 0; i < nums.length; i++) {                if (nums[i] == num) {                    return i;                }            }            return -1;        }        // 二分法查找、如果存在,返回排序后数组中的位置,如果不存在,返回-1        public static int binarySearch(int nums[], int num) {            // 前提有序数组            Arrays.sort(nums);            System.out.println();            // d定义地位和高位            int low = 0;            int high = nums.length - 1;            int mid = 0;            while (low <= high) {                mid = (low + high) / 2;                if (num < nums[mid]) {// 左侧找,修改高位                    high = mid - 1;                } else if (num > nums[mid]) {// 右侧找修改低位                    low = mid + 1;                } else {// num == nums[mid]                    return mid;                }            }            return -1;        }        // 交换数组中的元素(将数组中第i个和第j个元素进行交换)        public static void swap(int nums[], int i, int j) {            // nums[i]和num[j]进行互换            int t = nums[i];            nums[i] = nums[j];            nums[j] = t;        }        // 打印输出,显示数组中的元素        public static void showArray(int nums[]) {            for (int s : nums) {                System.out.println(s);            }        }    }    package com.niu.day31.array.sort;    public class TestUtil {        public static void main(String[] args) {            int arr[] = { 34, 56, 11, 45, 23, 78, 90 };            int num = 34;            // 冒泡排序            // ArraryUtil.bubbleSort(arr);            // 选择排序            // ArraryUtil.chooseSort(arr);            // 插入排序            // ArraryUtil.insertSort(arr);            // ArraryUtil.showArray(arr);            // int i = ArraryUtil.sort(arr, num);            // System.out.println((i == -1) ? "不存在" : "存在" + " 第" + i + "个元素位置");            int i = ArraryUtil.binarySearch(arr, num);            System.out.println((i == -1) ? "不存在" : "存在" + "     第" + i + "个元素位置");        }    }

2.二维数组:

定义:    int arr[][] = new int[行数][列数];赋值:    arr[0][0] = 10;    arr[0][1] = 20;    arr[0][2] = 20;    arr[1][0] = 10;    arr[1][1] = 34;    arr[1][2] = 45;arr.length--->数组的行数     arr[i].length---->数组的第i行的元素的个数遍历数组:(1)方法一:    for (int i = 0; i < arr.length; i++) {//外层控制行数        for (int j = 0; j < arr[i].length; j++) {//控制列数            System.out.print(arr[i][j] + "  ");        }        System.out.println();    }       (2)方法二:     for(int[] a:arr){    for(int aa:a){        System.out.println(aa);    }}

Demo:

public static void demo2() {/** 定义一个二维数组,其中行[3,5]随机数,列[4,7] 该二维数组为不规则数组 数组中元素范围[22,99] 求::::输出数组中元素* 2.统计数组中元素个数 3.对二维数组求和、平均值 4.找到最大值最小值及他们的位置 5.使用for的增强遍历数组* */            int count = 0;// 数组中元素个数            double sum = 0;// 和            double avg = 0;// 平均值            int minIndext = 0;// 最小值行下标            int min = 0;// 最小值列下标            int maxIndext = 0;// 最大值行下标            int max = 0;// 最大值列下标            // 不规则数组            int arr[][] = new int[(int) (Math.random() * (5 - 3 + 1) + 3)][];            for (int i = 0; i < arr.length; i++) {                arr[i] = new int[(int) (Math.random() * (7 - 4 + 1) + 4)];                count += arr[i].length;// arr[i].length每行元素的个数            }            System.out.println("数组中元素个数为:" + count);            for (int i = 0; i < arr.length; i++) {                for (int j = 0; j < arr[i].length; j++) {                    arr[i][j] = (int) (Math.random() * (99 - 22 + 1) + 22);// 给二维数组中每个元素赋值                    sum = sum + arr[i][j];// 求和                    avg = sum / count;// 求平均值                    // 求最小值                    if (arr[minIndext][min] > arr[i][j]) {                        minIndext = i;                        min = j;                    }                    // 求最大值                    if (arr[maxIndext][max] < arr[i][j]) {                        maxIndext = i;                        max = j;                    }                }            }            System.out.println("数组元素包括:");            for (int[] is : arr) {                for (int i : is) {                    System.out.print(i + "   ");                }                System.out.println();            }            System.out.println("和为:" + sum);            System.out.println("平均值为:" + avg);            System.out.println("最小值为:" + arr[minIndext][min]);            System.out.println("最小值位置为:   第" + (minIndext + 1) + "行,第" + (min + 1) + "列");            System.out.println("最大值为:" + arr[maxIndext][max]);            System.out.println("最大值位置为:   第" + (maxIndext + 1) + "行,第" + (max + 1) + "列");        }       
0 0