总结:运行显示数组下标越界说明,数组长度a.length.表示数组的长度,但索引值是要减一的。勿忘

package com.c2;

//冒泡排序 //从小到大的顺序排列
public class MAO {
	public static void main(String[] args) {
		int a[] = { 2, 1, 67, 7, 4, 8 };
		for (int i = 0; i < a.length; i++) {
			System.out.println(a[i] + " ");
		}// 如果这里a.length不减一,就会数组越界,数组长度减一则是索引值
		int temp;// 存储交换的变量值
		for (int i = 0; i < a.length - 1; i++) {// 比较n-1轮
			for (int j = 0; j < a.length - 1 - i; j++) {// 第i轮需要比较a.length-i次。再减一,防止数组下标越界

				if (a[j] < a[j + 1]) {// 从大到小
					temp = a[j];
					a[j] = a[j + 1];
					a[j + 1] = temp;

				}

			}
		}
		System.out.println();
		System.out.print("排序后的顺序为:");
		for (int i = 0; i < a.length; i++) {
			System.out.println(a[i] + " ");
		}

	}
}

  

相关文章:

  • 2021-06-27
  • 2021-08-16
  • 2021-08-22
  • 2021-11-19
  • 2022-12-23
  • 2021-11-07
猜你喜欢
  • 2021-10-01
  • 2021-06-16
  • 2021-04-07
  • 2021-08-01
  • 2022-02-13
  • 2021-10-04
  • 2021-07-01
相关资源
相似解决方案