一维数组的有序插入
思路
代码
点击查看代码
import java.util.Scanner;
/**
* @author LittleBear
* @date 2024-02-02 - 16:57
*/
public class seqInsertion {
public static void main(String[] args) {
System.out.println("please input your num:");
Scanner myScanner = new Scanner(System.in);
int insertNum = myScanner.nextInt();
int len = 10;
int arr[] = new int[len];
for (int i = 0; i < len; i++) {
arr[i] = (int)(Math.random()*100+1);
// System.out.println(arr[i]);
}
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]){
int tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
}
}
}
int index = -1;
for (int i = 0; i < arr.length; i++) {
if (insertNum <= arr[i]){
index = i;
break;
}
}
if (index == -1){
index = arr.length;
}
int[] newArr = new int[arr.length+1];
for (int i = 0, j = 0; i < newArr.length; i++) {
if (i != index){
newArr[i] = arr[j];
j++;
}
else{
newArr[i] = insertNum;
}
}
arr = newArr;
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " " );
}
}
}
杨辉三角(二维数组)
思路
代码
点击查看代码
/**
* @author LittleBear
* @date 2024-02-02 - 14:50
*/
public class yanghui {
public static void main(String[] args) {
int[][] yang = new int[12][];
for (int i = 0; i < yang.length; i++) {
yang[i] = new int[i+1];//给每一个一维数组开辟空间
for (int j = 0; j < yang[i].length; j++) {
if(j == 0 || j== yang[i].length - 1){//给每一行的第一个和最后一个元素赋值
yang[i][j] = 1;
}
else{//中间元素赋值
yang[i][j] = yang[i-1][j-1] + yang[i-1][j];
}
}
}
for (int i = 0; i < yang.length; i++) {
for (int j = 0; j < yang[i].length; j++) {
System.out.print(yang[i][j] + "\t");
}
System.out.println();
}
}
}
冒泡排序(一维数组)
代码
点击查看代码
/**
* @author LittleBear
* @date 2024-02-02 - 14:49
*/
public class sort {
public static void main(String[] args) {
int len = 10;
int[] arr = new int[10];
for (int i = 0; i < len; i++) {
arr[i] = (int)(Math.random()*100)+1;
// System.out.println(arr[i]);
}
for (int i = 0; i < len -1; i++) {
for (int j = 0; j < len - i -1; j++) {
if(arr[j] > arr[j+1]){
int tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
}
}
}
for (int i = 0; i < len; i++) {
System.out.print(arr[i] + " ");
}
}
}