数组是一种数据结构,用来存储同一类型值的集合。通过一个整型下标可以访问数组中的每一个值。
声明数组
声明数组的三种方式:
// 方式一
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]
冒泡排序
冒泡排序的基本思想是,对相邻的元素进行两两比较,顺序相反则进行交换,这样,每一趟会将最小或最大的元素“浮”到顶端,最终达到完全有序。
算法实现:
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));
}
}
}
输出结果:
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]
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。