数组及排序算法

来源:互联网 发布:房卡 娄底放炮罚 源码 编辑:程序博客网 时间:2024/06/06 03:10

1.数组概述

  • 数组是存储同一种数据类型多个元素的集合,也可以看成是一个容器。
  • 数组既可以存储基本数据类型,也可以存储引用数据类型。
  • 数组可以存储多个数据,而且可以对数据编号,从0开始,操作元素可以通过编号(下表、索引)完成。

2.数组的定义方式:

//方式一:元素类型[] 数组名=new 元素类型[数组的长度]int[] arr=new int[5];arr[0]=7;arr[1]=5;arr[2]=9;arr[3]=3;arr[4]=8;//方式二int a[]={10,20,32,30,40};//方式三int a[]=new int[]{10,20,32,30,40};

3.数组操作常见错误

  • ArrayIndexOutOfBoundsException:数组索引越界异常
  • NullPointerException:空指针异常,原因:数组已经不在指向堆内存了。而你还用数组名去访问元素。
int[] arr = {1,2,3};arr = null;System.out.println(arr[0]);

4.数组求和

public class ArraySum {    public static void main(String[] args) {        int[] arr1 = { 1, 2, 3, 4, 5 };        int sum = arrSum(arr1);        System.out.println(sum);    }    public static int arrSum(int[] arr) {        int sum = 0;        for (int i = 0; i < arr.length; i++) {            sum = +arr[i];        }        return sum;    }}
public class ArraySum2 {    public static void main(String[] args) {        int[] arr = { 1, 2, 3, 4, 5 };        int sum = 0;        for (int i = 0; i < arr.length; i++) {            sum += arr[i];        }        System.out.println(sum);    }}

5.数组求最大值

public class ArrayMax {    public static void main(String[] args) {        int[] arr1 = { 56, 135, 67, 87, 89, 88 };        int max = getMax(arr1);        System.out.println(max);    }    public static int getMax(int[] arr) {        //定义变量,初始化数组中的任意一个元素        int max = arr[0];        //数组遍历        for (int i = 1; i < arr.length; i++) {            if (arr[i] > max) {                max = arr[i];            }        }        return max;    }}
public class ArrayMax {    public static void main(String[] args) {        int[] arr1 = { 56, 135, 67, 87, 89, 88 };        int max = getMax(arr1);        System.out.println(max);    }    public static int getMax(int[] arr) {        //初始化数组中的任意一个角标        int max = 0;        for (int i = 1; i < arr.length; i++) {            if (arr[i] > arr[max]) {                max = i;            }        }        return arr[max];    }}

6.选择排序

public class ArrayTest {    public static void main(String[] args) {        int[] arr = { 12, 9, 23, 77, 6, 34 };        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;                }            }        }        for (int i = 0; i < arr.length; i++) {            System.out.println(arr[i]);        }    }}

选择排序

原创粉丝点击