作者:Not-Only-For曾广超 | 来源:互联网 | 2023-10-15 10:41
实验要求
1、输出杨辉三角
2、冒泡排序
3、选择排序
4、插入排序
5、创建要给长度为6的int类型数组,要求数组元素的值再1-30之间,且随机赋值。同时要求数组元素各不相同
实验过程
1、输出杨辉三角
int [] arr &#61; new int[10];arr[0] &#61; 1; System.out.println(Arrays.toString(arr));arr[0] &#61; arr[1] &#61; 1; System.out.println(Arrays.toString(arr));for (int i &#61; 2; i < 10; i&#43;&#43;){ arr[i] &#61; arr[i - 1]; for (int j &#61; i - 1; j > 0; j--){ arr[j] &#61; arr[j] &#43; arr[j - 1]; }System.out.println(Arrays.toString(arr));}
2、冒泡排序
int [] arr &#61; new int[]{23,11,44,25,67,43,62};int i, j, t;for (i &#61; 0; i < arr.length - 1; i&#43;&#43;){for (j &#61; 0; j < arr.length - i - 1; j&#43;&#43;){if (arr[j] > arr[j &#43; 1]){t &#61; arr[j];arr[j] &#61; arr[j &#43; 1];arr[j &#43; 1] &#61; t;}}}System.out.println(Arrays.toString(arr));
3、选择排序
int [] arr &#61; new int[]{23,11,44,25,67,43,62};int min, t, i, j;for (i &#61; 0; i < arr.length - 1; i&#43;&#43;){min &#61; i;for (j &#61; i &#43; 1; j < arr.length; j&#43;&#43;){if (arr[j] < arr[min]){min &#61; j;}}if (min !&#61; i){t &#61; arr[min];arr[min] &#61; arr[i];arr[i] &#61; t;}}System.out.println(Arrays.toString(arr));
4、插入排序
int [] arr &#61; new int[]{23,11,44,25,67,43,62};int i, j, t;for (i &#61; 1; i < arr.length; i&#43;&#43;){t &#61; arr[i];for (j &#61; i - 1; j >&#61; 0; j--){if (t > arr[j]){break;}else {arr[j &#43; 1] &#61; arr[j];}}arr[j &#43; 1] &#61; t;}System.out.println(Arrays.toString(arr));
5、创建要给长度为6的int类型数组&#xff0c;要求数组元素的值再1-30之间&#xff0c;且随机赋值。同时要求数组元素各不相同
Random r &#61; new Random();int [] arr &#61; new int[6];int random, a, j &#61; 0;while (j < arr.length) {random &#61; r.nextInt(30) &#43; 1;a &#61; 0;for (int i : arr) {if (random &#61;&#61; i) {a&#43;&#43;;break;}}if (a &#61;&#61; 0){arr[j] &#61; random;j&#43;&#43;;}}