文章目录
- 嵌套循环
- 数组
- 数组的定义
- 数组的初始化
- 数组在内存中的理解
- 两个数组的内存图
- 数组的两大异常:
- 冒泡排序
- 插入排序
嵌套循环
嵌套循环练习:
for (int i = 1; i <=4; i++) {
System.out.println("");
for (int j = 1; j <= 5; j++) {
System.out.print("*");
}
}
for (int i = 0; i <=5; i++) {
System.out.println("");
for (int j = 0; j
for (int i = 1; i <=9 ; i++) {
for (int j=1;j<=i;j++){
System.out.print(j+"*"+i+"="+(j*i)+"\t");
}
System.out.println("");
}
数组
数组的定义
数组的初始化
数组在内存中的理解
两个数组的内存图
数组的两大异常:
数组索引越界异常
空指针异常
数组练习
冒泡排序
冒泡排序代码示范:
int [] arr = {34,253,1,658,45,111};
int temp;
for(int i = 0; i < arr.length-1; i++) {//轮数
for(int j = 0; j < arr.length-1 - i; j++) {//次数
//比较 和 互换
if(arr[j] > arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
for(int a : arr) {
System.out.println(a);
冒泡排序练习:
public static void main(String[] args) {
char[] a=new char[]{'a','c','u','b','e','p','f','z'};
System.out.println("原字符序列:"+Arrays.toString(a));
char temp=a[0];
for (int i = 0; i a[j+1]){
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
System.out.println("升序排序后:"+Arrays.toString(a));
for (int i = 0; i
插入排序
插入排序代码示范:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入你想插入的值:");
int num = input.nextInt();
int[] a = new int[11];//动态定义数组
a[0] = 10;
a[1] = 20;
a[2] = 30;
a[3] = 40;
a[4] = 50;
a[5] = 60;
a[6] = 70;
a[7] = 80;
a[8] = 90;
a[9] = 100;
int maxNum = a[0];
for (int i = 0; i < a.length; i++) {
if (a[i] > maxNum) {
maxNum = a[i];
}
}
if (num > maxNum) {
a[a.length - 1] = num;
} else {
int index = -1;
for (int i = 0; i < a.length; i++) {
if (a[i] > num) {
index = i;
break;
}
}
for (int i = a.length - 1; i > index; i--) {
a[i] = a[i - 1];
}
a[index] = num;
}
System.out.println(Arrays.toString(a));
}
插入排序练习:
public static void main(String[] args) {
char[] a=new char[9];
a[0]='a';
a[1]='b';
a[2]='c';
a[3]='e';
a[4]='f';
a[5]='p';
a[6]='u';
a[7]='z';
char temp='m';
System.out.print("原字符序列:");
for (int i = 0; i index;i--){
a[i]=a[i-1];
}
a[index]=temp;
System.out.print("插入后的字符序列是:");
for (int i = 0; i < a.length ; i++) {
System.out.print(a[i]+"\t");
}
}