按排序顺序将元素插入到数组中

时间:2014-10-01 07:08:59

标签: java arrays insert

我试图按排序顺序将元素添加到数组中。

这是我的代码:

public class SortedInsertion {

    public static void main(String[] args) {

        int[] arr=new int[6];
        arr[0]=5;
        arr[1]=6;
        arr[2]=9;
        arr[3]=11;
        System.out.println(Arrays.toString(arr));
        insert(7,arr);


    }

    public static void insert(int val,int[] arr){
        int i;
        for(i=0;i<arr.length-1;i++){

            if(arr[i]>val)
                break;
        }
        for(int k=i;k<arr.length-1;k++){
            arr[k+1]=arr[k];
            arr[i]=val;
        }
        System.out.println(Arrays.toString(arr));


    }

}

我得到的输出为: [5,6,9,11,0,0]

[5,6,7,9,9,9]

但是正确的出局是

5,6,9,11,0,0

5,6,7,9,11,0

8 个答案:

答案 0 :(得分:1)

for循环

中存在问题
for(i=0;i<arr.length-1;i++){}

它应该迭代到i<arr.length

for(i=0;i<arr.length;i++){}

答案 1 :(得分:1)

下面

arr[k+1]=arr[k];

您将使用之前的值覆盖每个下一个数组元素。你应该扭转你的循环并从数组的末尾移开,向前移动所有元素,直到找到正确的位置,即:

public static void insert(int val, int[] arr) {
    for(int i = arr.length - 1; i > 0; i--) {
        if (arr[i] == 0) continue; // skip last elements to avoid array index out of bound
        arr[i + 1] = arr[i];       // shift elements forward
        if (arr[i] <= val) {       // if we found the right spot
            arr[i] = val;          // place the new element and
            break;                 // break out the loop
        }
    }
    System.out.println(Arrays.toString(arr));
}

答案 2 :(得分:1)

更改insert方法,如下所示:

    public static void insert(int val,int[] arr){
      int i;
      for(i=0;i<arr.length-1;i++){
        if(arr[i]>val)
          break;
      }
      for(int k=arr.length-2; k>=i; k--){
        arr[k+1]=arr[k];            
      }
      arr[i]=val;
      System.out.println(Arrays.toString(arr));

    }

答案 3 :(得分:0)

另一种解决方法是使用List和collections.sort方法。

List<Integer> list = new ArrayList<Integer>(); 
  for (int i = 0; i < arr.length; i++) { 
  list.add(arr[i]); 
  } 
  list.add(val);

  Collections.sort(list);

 int[] result = list.stream().mapToInt(Integer::intValue).toArray();
 System.out.println(Arrays.toString(result));

希望这个解决方案有所帮助。

答案 4 :(得分:0)

Java代码,

public static void insertElementInSortedArr(int a[], int val) {

        int n[] = new int[a.length + 1];
        int j = 0;
        boolean isAdded = false;
        for (int i = 0; i < a.length; i++) {
            if (a[i] < val) {
                n[j] = a[i];
                j++;
            } else {
                if (!isAdded) {
                    n[j] = val;
                    j = j + 1;
                    isAdded = true;
                }
                n[j] = a[i];
                j = j + 1;
            }
        }
    }

答案 5 :(得分:0)

public class InsertInSortedArray {
        public static void main(String[] args) {
            int arr[] = {5, 6, 9, 11};
            Arrays.sort(arr);
            int k = 7;
            int index = findIndexToBeInserted(arr, k, 0, arr.length - 1);
            ArrayList<Integer> al = new ArrayList<>();
            for (int i : arr)
                al.add(i);

            al.add(index, k);
            for (int i : al)
                System.out.println(i);
        }

    private static int findIndexToBeInserted(int[] arr, int k, int start, int end) {
            if (k == 0)
                return 0;

            int mid = (start + end) / 2;

            if (k > arr[mid] && k < arr[mid + 1])
                return mid + 1;

            if (arr[mid] < k)
                return findIndexToBeInserted(arr, k, mid + 1, end);

            return findIndexToBeInserted(arr, k, start, mid - 1);
        }
    }

答案 6 :(得分:0)

说实话,所讨论的数组并不是真正按以下顺序排序:[0, 0, 5, 6, 9, 11]
它是一个“零尾”数组:[5, 6, 9, 11, 0, 0]
因此,要将值插入该数组,需要知道占用了多少个元素。如果将此值提供给方法,它将具有O(log n)复杂度。否则,它需要在插入方法内部实现计数。

/**
* @throws ArrayIndexOutOfBoundsException when the array is full and the value to be inserted is greater than the last element
*/
private static void insertToZeroTailedArray(int val, int[] arr) {
    // an O(n) operation to count occupied elements
    int elementsCount = 0;
    for (int i = arr.length - 1; i >= 0; i--) {
        if (arr[i] != 0) {
            elementsCount = i + 1;
            break;
        }
    }

    // binarySearch returns a negative position to insert if the value was not found
    int index = Arrays.binarySearch(arr, 0, elementsCount, val);
    if (index != 0) {
        int pos = index < 0
                ? -index - 1 // val not found, it is need to be inserted at (-index)-1 position
                : index;     // val found but we are going to insert it again

        // shift the array to right and drop last element because of the array bounds
        System.arraycopy(arr, pos, arr, pos + 1, arr.length - pos - 1);
        arr[pos] = val;
    } else {
        // the case when value is found at 0 position
        System.arraycopy(arr, 0, arr, 1, arr.length - 1);
        arr[0] = val;
    }
}

使用O(log n)复杂度对真正排序的数组进行操作的另一种方法:

private static void insertToReallySortedArray(int val, int[] arr) {
    int index = Arrays.binarySearch(arr, val);
    if (index != 0) {
        int pos = index < 0 ? -index - 1 : index;
        System.arraycopy(arr, pos, arr, pos + 1, arr.length - pos - 1);
        arr[pos] = val;
    } else {
        System.arraycopy(arr, 0, arr, 1, arr.length - 1);
        arr[0] = val;
    }
}

基于出色的answer

答案 7 :(得分:0)

完全不清楚插入函数应如何工作,而不知道已经占用的字段数?

public static void insert( int n, int occupied, int[] array ) {
  if( n >= array[occupied - 1] )
    array[occupied] = n;
  else
    for( int i = 0; i < array.length; i++ ) {
      int n1 = array[i];
      int n2 = array[i + 1];
      if( n1 > n || n1 < n && n2 >= n ) {
        if( n1 > n ) i--;
        System.arraycopy( array, i + 1, array, i + 2, occupied - i - 1 );
        array[i + 1] = n;
        break;
      }
    }
}


从上述示例中调用:

…
arr[3]=11;
int occupied = 4;
insert( 7, occupied, arr );  // [5, 6, 7, 9, 11, 0]

如果ArrayIndexOutOfBoundsException,则未选中occupied >= array.length的半身像