public class Test {
public static void main(String args[]) {
String[] array = {"a", "b", "c", "d"}
System.out.println(java.util.Arrays.toString(array))
String[] array2 = ArrayUtilities.insert(array, "e", 2)
System.out.println(java.util.Arrays.toString(array2))
String[] array3 = ArrayUtilities.remove(array2, 3)
System.out.println(java.util.Arrays.toString(array3))
}
}
class ArrayUtilities {
public static int[] insert(int[] original, int newElement, int pos) {
int length = original.length
int[] dest = new int[length + 1]
System.arraycopy(original, 0, dest, 0, pos)
dest[pos] = newElement
System.arraycopy(original, pos, dest, pos + 1, length - pos)
return dest
}
@SuppressWarnings("unchecked")
public static <T>T[] insert(T[] original, T newElement, int pos) {
int length = original.length
T[] dest = (T[]) java.lang.reflect.Array
.newInstance(newElement.getClass(), length + 1)
System.arraycopy(original, 0, dest, 0, pos)
dest[pos] = newElement
System.arraycopy(original, pos, dest, pos + 1, length - pos)
return dest
}
public static int[] remove(int[] original, int pos) {
int length = original.length
int[] dest = new int[length - 1]
System.arraycopy(original, 0, dest, 0, pos)
System.arraycopy(original, pos + 1, dest, pos, length - pos - 1)
return dest
}
@SuppressWarnings("unchecked")
public static <T>T[] remove(T[] original, int pos) {
int length = original.length
T[] dest = (T[]) java.lang.reflect.Array
.newInstance(original.getClass().getComponentType(), length - 1)
System.arraycopy(original, 0, dest, 0, pos)
System.arraycopy(original, pos + 1, dest, pos, length - pos - 1)
return dest
}
}
题目要求是插入原有序列,并且存储在数组中所以在要插入的位置之后所有的元素都要后移一个位置——不能前移,因为已经到0了
你的错误在for循环内部一直比较a[i]和a[i+1],没刚读入的a[9]什么事,一直到i=8了才会涉及到a[9],不过也就交换了8和9的位置而已,根本不算插入
以下程序可以正确编译运行
void main()
{
int a[10]={0,1,3,4,5,6,7,8,9}
int i,t
int found = 0//是否已经插入的标志位
scanf("%d",&a[9])
t= a[9]
for(i=0i<9i++)
{
if(a[i]>t &&!found)//判断是否为插入位置
{
t=a[i]//插入数据并设置标志位
a[i]=a[9]
found = 1
}
else if(found) //已经插入,之后数据全部后移1格
{
a[9] = a[i]
a[i] = t
t = a[9]
}
}
for(i=0i<10i++)
printf("%5d",a[i])
printf("\n")
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)