JAVA已知一个数组中的数有序排列,编程实现插入一个数后,依然有序,怎么操作?

如题所述

第1个回答  2018-02-21
有两种方法,代码都给你
第一种,就是常规的想法,:建个数组,然后逐个比较,这应该也是出题人的考察点,但是这种题不适合在java理出,一般C语言愿意有这样的问题.

import java.util.Arrays;
public class $ {
public static void main(String[] args) { Integer[] arr = { 11, 22, 33, 44, 55, 66, 77, 88, 99 };
System.out.println("插入前:" + Arrays.deepToString(arr));
Integer[] brr = insert(arr, 60);
System.out.println("插入前:" + Arrays.deepToString(brr));
}

private static Integer[] insert(Integer[] arr, int num) {
Integer[] brr = new Integer[arr.length + 1];
int idx = 0;
boolean hasInsert = false;
for (int i = 0; i < arr.length; i++) {

if (hasInsert) {
brr[idx++] = arr[i];
continue;
}

if (arr[i] > num) {
brr[idx++] = num;
hasInsert = true;
}
brr[idx++] = arr[i];
}
return brr;
}
}

第二种就是利用java api里的方法,实现简单,但是效率不够,而且也违背了出题人的意愿,可做了解
private static Integer[] insert(Integer[] arr, int num) {
List<Integer> data = new ArrayList<Integer>();
for (Integer a : arr) {
data.add(a);
}
data.add(num);

Collections.sort(data);
return data.toArray(new Integer[0]);
}本回答被网友采纳
相似回答