首页 > 解决方案 > 尝试在排序数组中插入元素时出错

问题描述

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

我的代码就在下面。

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]);
    }   
}

直到添加元素和删除工作正常但插入新元素工作不正常。

标签: java

解决方案


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]

推荐阅读