Java —— 数组

数组是一种数据结构,用来存储同一类型值的集合。经过一个整型下标能够访问数组中的每个值。html

声明数组

声明数组的三种方式:java

// 方式一
int [] a = {2, 3, 5, 7, 11, 13};

// 方式二
int [] b = new int[]{17, 19, 23, 29, 31, 37};

// 方式三
int [] c = new int[100];

一旦建立了数组,就不能再改变它的大小。算法

数组排序

Arrays.sort(type[] a)

采用优化的快速排序算法对数组进行排序。数组

示例:数据结构

int[] a = { 5, 7, 11, 2, 3, 13 };
System.out.println("排序前:" + Arrays.toString(a));
Arrays.sort(a);
System.out.println("排序后:" + Arrays.toString(a));

输出结果:优化

排序前:[5, 7, 11, 2, 3, 13]
排序后:[2, 3, 5, 7, 11, 13]

冒泡排序

冒泡排序的基本思想是,对相邻的元素进行两两比较,顺序相反则进行交换,这样,每一趟会将最小或最大的元素“浮”到顶端,最终达到彻底有序。spa

冒泡排序

算法实现:code

public class Hello {
    public static void main(String[] args) {
        int[] a = { 7, 5, 13, 11, 2, 3 };
        Hello.bubbleSort(a);
    }
    public static void bubbleSort(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;
                }
            }
            System.out.println(i + ":" + Arrays.toString(a));
        }
    }
}

输出结果:htm

5:[5, 7, 11, 2, 3, 13]
4:[5, 7, 2, 3, 11, 13]
3:[5, 2, 3, 7, 11, 13]
2:[2, 3, 5, 7, 11, 13]
1:[2, 3, 5, 7, 11, 13]

参考

相关文章
相关标签/搜索