day1026

定义数组

  方式1(推荐,更能表明数组类型)

  type[] 变量名 = new type[数组中元素的个数];

  比如:

  int[] a = new int[10];

  数组名,也即引用a,指向数组元素的首地址。

  方式2 定义时直接初始化

  type[] 变量名 = new type[]{逗号分隔的初始化值};

 

  其中红色部分可省略,所以又有两种:

 

  int[] a = {1,2,3,4};

 

  int[] a = new int[]{1,2,3,4};

 

  其中int[] a = new int[]{1,2,3,4};的第二个方括号中不能加上数组长度,因为元素个数是由后面花括号的内容决定的。

 

数组长度

 

  Java中的每个数组都有一个名为length的属性,表示数组的长度。

 

  length属性是public final int的,即length是只读的。数组长度一旦确定,就不能改变大小。

简单选择排序和冒泡排序:

 

package com.lovo;

public class Test02 {

    public static void main(String[] args) {
        int[] a = new int[5];
        System.out.print("排序前: ");
        for(int i = 0; i < a.length; i++) {
            a[i] = (int) (Math.random() * 99 + 1);
            System.out.print(a[i] + "  ");
        }
        // 简单选择排序
        for(int i = 0; i < a.length - 1; i++) {
            int minIndex = i;
            for(int j = i + 1; j < a.length; j++) {
                if(a[j] < a[minIndex]) {
                    minIndex = j;
                }
            }
            if(minIndex != i) {
                int temp = a[i];
                a[i] = a[minIndex];
                a[minIndex] = temp;
            }
        }
        
        System.out.print("\n排序后: ");
        for(int x : a) {
            System.out.print(x + "  ");
        }
    }
}

 

package com.lovo;

public class Test03 {

    public static void main(String[] args) {
        int[] a = new int[5];
        System.out.print("排序前: ");
        for(int i = 0; i < a.length; i++) {
            a[i] = (int) (Math.random() * 99 + 1);
            System.out.print(a[i] + "  ");
        }
        // 冒泡排序
        
        boolean swapped = true;    // 有没有发生过交换
        for(int i = 1; swapped && i <= a.length - 1; i++) {
            swapped = false;    // 表示尚未发生交换
            for(int j = 0; j < a.length - i; j++) {
                if(a[j] > a[j + 1]) {
                    int temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                    swapped = true;
                }
            }
        }
        
        System.out.print("\n排序后: ");
        for(int x : a) {
            System.out.print(x + "  ");
        }
    }
}

 

posted on 2014-10-26 18:27  Barneyman  阅读(125)  评论(0)    收藏  举报

导航