java - 尝试在排序数组中插入元素时出错
问题描述
我正在尝试在数组中添加一个元素,然后对其进行排序。但是当我尝试在排序数组中再次插入元素时,它向我展示了一个数组。请帮助我了解如何在排序数组中插入元素。
我的代码就在下面。
import java.util.Scanner;
public class InsertionSort {
public static void main(String[] args) {
int n, temp, i, count = 0;
Scanner s = new Scanner(System.in);
System.out.println("Enter number of Elements");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements");
for (i = 0; i < n; i++) {
a[i] = s.nextInt();
}
for (i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.println("Ascending Order is :");
for (i = 0; i < n - 1; i++) {
System.out.print(a[i] + ",");
}
System.out.println(a[n - 1]);
System.out.println("Select the number which you want to delete : ");
int del = s.nextInt();
for (i = 0; i < n; i++) {
if (a[i] == del) {
for (int j = i; j < (n - 1); j++) {
a[j] = a[j + 1];
}
count++;
break;
}
}
System.out.print("\nNow the New Array is :\n");
for (i = 0; i < (n - 1); i++) {
System.out.println(a[i] + " ");
}
System.out.println("Write a number which you want to insert :");
int insert = s.nextInt();
for (i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (insert > a[j]) {
temp = insert;
insert = a[j];
a[j] = temp;
}
}
}
System.out.println("Ascending Order is :");
System.out.print(insert + ",");
System.out.println(a[n + 1]);
}
}
直到添加元素和删除工作正常但插入新元素工作不正常。
解决方案
public static void insertIntoSortedArray(int[] arrSorted, int val) {
int i = 0;
// find insert position - i
while (i < arrSorted.length - 1 && arrSorted[i] < val) {
i++;
}
// shift array 1 position right (ignore last element)
if (i < arrSorted.length - 1)
System.arraycopy(arrSorted, i, arrSorted, i + 1, arrSorted.length - i - 1);
// insert 1 element
arrSorted[i] = val;
}
演示:
int[] arr = { 1, 2, 3, 5, 6 };
insertIntoSortedArray(arr, 4); // [1, 2, 3, 4, 5]
insertIntoSortedArray(arr, 7); // [1, 2, 3, 4, 7]
insertIntoSortedArray(arr, -1); // [-1, 1, 2, 3, 4]
推荐阅读
- google-cloud-platform - 在 GCP 控制台中创建磁盘显示加载失败
- google-chrome - google chrome devtools 元素/属性的问题
- ios - 当我尝试运行我的项目时,我收到此错误“Command PrecompileSwiftBridgingHeader failed with a nonzero exit code”
- python - 如何pytest装饰器分配给多个功能
- javascript - 当用户在图片上向右或向左滑动时执行一个或其他功能 - RxJS
- c# - 创建共享链接 MS Graph BadRequest
- polyline - Edge data from generated polyline in Meshlab
- azure - Whitesource Bolt 无法生成报告
- xml - 为什么从 XSD 到 XML 样本到 XSD 样本的往返失败?
- typescript - 扩展客户端缺少功能