用Java编写 有一个已经排序好的数组 现在输入一个数字,要求按原来的规律插入这个数
时间: 2024-04-05 08:02:55 浏览: 45
您好!以下是使用Java编写的将数字按原来规律插入已排序数组的示例代码:
```java
public class InsertIntoSortedArray {
public static void main(String[] args) {
int[] sortedArray = {10, 20, 30, 40, 50};
int numberToInsert = 35;
System.out.println("Original sorted array: ");
printArray(sortedArray);
sortedArray = insertIntoSortedArray(sortedArray, numberToInsert);
System.out.println("Array after inserting " + numberToInsert + ": ");
printArray(sortedArray);
}
public static int[] insertIntoSortedArray(int[] sortedArray, int number) {
int[] newArray = new int[sortedArray.length + 1];
int i = 0;
// Find the correct position to insert the number
while (i < sortedArray.length && sortedArray[i] < number) {
newArray[i] = sortedArray[i];
i++;
}
// Insert the number at the correct position
newArray[i] = number;
// Copy the remaining elements from the original array to the new array
while (i < sortedArray.length) {
newArray[i + 1] = sortedArray[i];
i++;
}
return newArray;
}
public static void printArray(int[] array) {
for (int num : array) {
System.out.print(num + " ");
}
System.out.println();
}
}
```
在这段代码中,我们定义了一个`insertIntoSortedArray`方法,该方法接收一个已排序的数组和要插入的数字。我们创建一个新的数组`newArray`,长度比原数组多1,然后遍历原数组,找到要插入的数字应该在的位置,并将前面的元素复制到新数组中。最后,将要插入的数字插入到正确的位置,并将原数组剩余的元素复制到新数组中。
希望这个示例能够帮助您!如有任何疑问,请随时提问。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)