有一個已經排好序的數組。現輸入一個數,要求按原來的規律將它插入數組中。




import java.util.Scanner;

public class InsertNum {

	public static void main(String[] args) {
		// 思路:創建2個數組,把第一個數組的元素遍歷到第二個數組中,然后把要插入的元素與數組中的元素進行比較。
		int[] arr1 = new int[] { 1, 4, 5, 7, 9 };
		int index = arr1.length;
		System.out.println("請輸入一個數");
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int[] arr2 = new int[arr1.length + 1];
		System.out.println("插入元素之前:");
		// 把第一個數組的元素遍歷到第二個數組中
		for (int i = 0; i < arr1.length; i++) {
			arr2[i] = arr1[i];
			System.out.print(arr2[i] + "  ");
		}
		System.out.println();
		// 把要插入的元素與數組中的元素進行比較,如果要插入的元素小於數組中的元素,把當前的下標給index.
		for (int j = 0; j < arr2.length; j++) {
			if (n < arr2[j]) {
				index = j;
				break;
			}
		}
		// 依次把index之后的數組的元素的值。給它的下一個下標。
		for (int x = arr2.length - 1; x > index; x--) {
			arr2[x] = arr2[x - 1];
		}
		// 把要插入的元素的值賦值給index.
		arr2[index] = n;
		System.out.println("插入元素之后:");
		// 遍歷插入元素后的數組
		for (int y = 0; y < arr2.length; y++) {
			System.out.print(arr2[y] + "  ");
		}
	}
}






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM