gpt4 book ai didi

java - 尝试在排序数组中插入元素时出现错误

转载 作者:行者123 更新时间:2023-12-02 10:27:22 24 4
gpt4 key购买 nike

我正在尝试在数组中添加一个元素,然后对其进行排序。但是当我尝试在已排序的数组中再次插入元素时,它会向我显示一个数组。请帮助我了解如何在排序数组中插入元素。

我的代码就在下面。

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]

关于java - 尝试在排序数组中插入元素时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53849303/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com