如何在有序数组中插入一个数?如1,2,3,5,6中插入4?急等

如何在有序数组中插入一个数?如1,2,3,5,6中插入4?急等,第1张

从头逐一访问数组元素

判断当前元素是否小于等于要插入的数

是:继续访问下一个数

否:记录位置退出循环

将记录元素开始到最后一个元素均向后移动复制1个元素位置,空出来的存放插入元素

程序:

#include<stdio.h>

#define MAXLEN 10

int fia(int *a,int n,int x) { int i,b

  for ( i=0,b=ni<ni++ ) if ( a[i]>x ) { b=i break }

  n++

  for ( i=bi<ni++ ) { b=a[i] a[i]=x x=b }

  return n

}

void main() { int a[N]={1,2,3,5,6},i,n=5

  n=fia(a,n,4) for ( i=0i<ni++ ) printf("%d ",a[i]) printf("\n")

}

Dim numbers(9) As Integer

Dim output As String = ""

For i As Integer = 0 To numbers.Length - 1

numbers(i) = i * 10

output = output &numbers(i) &vbTab

Next i

TextBox1.Text = output

Dim key As Single

Dim numbers(11) As Integer

For i As Integer = 0 To numbers.Length - 1

numbers(i) = i * 10

Next i

key = InputBox("输入要插入的元素", "实验5.5 数组元素的有序插入")

For i = 0 To UBound(numbers) - 1

If key <numbers(i) Then

For j As Integer = UBound(numbers) - 1 To i Step -1

numbers(j + 1) = numbers(j)

Next

numbers(i) = key

Exit For

End If

Next

TextBox1.Text = ""

For i As Integer = 0 To UBound(numbers) - 1

TextBox1.Text &= numbers(i) &vbTab

Next i

实验5.7 : Dim k As Single

Dim flag As Object

k = 0

For i = 0 To UBound(a)

flag = True

For j = 0 To UBound(b)

If b(j) = a(i) Then

flag = False

Exit For

End If

Next

If flag = True Then

TextBox3.Text &= CStr(a(i)) + " "

End If

Next

Dim i, j As Single

For i = 0 To UBound(a)

TextBox1.Text &= a(i) &" "

Next

For j = 0 To UBound(b)

TextBox2.Text &= b(j) &" "

Next

在Java中,数组的长度是不可以改变的,所以你想往一个数组里面添加元素是不可以的。但是你可以把这个数组里面的元素和要添加的元素一起放到另一个数组里面。你的方法我给改了一下,你自己看看吧!

class ArryFind

{

public static void main(String[] args)

{

int[]b={1,12,33,47,58,72,97,167}

printArr(b)

int[]arrys=inst(b,36)

printArr(arrys)

}

public static int search(int []arry, int key)

{

for (int i=0i<arry.length-1 i++ )

{

if (key<=arry[i])

return i

}

return arry.length-1

}

public static int[] inst(int[]arry, int key)

{

int result=search(arry,key)

System.out.println("result="+result)

int []arry1 = new int [arry.length+1]

for (int j=0j<=arry1.length-1 j++ )

{

if (j<result)

arry1[j]=arry[j]

else if (j>result)

arry1[j]=arry[j-1]

else

arry1[result]=key

}

System.out.print("arry1=")

printArr(arry1)

System.out.println("")

System.out.print("arry=")

printArr(arry)

System.out.println("")

arry=arry1

System.out.print("arry1=")

printArr(arry1)

System.out.println("")

System.out.print("arry=")

printArr(arry)

System.out.println("")

return arry1

}

public static void printArr(int []arry)

{

for (int i=0i<arry.length i++ )

{

if (i<arry.length-1)

System.out.print(arry[i]+",")

else

System.out.println(arry[i])

}

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11946555.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-19
下一篇 2023-05-19

发表评论

登录后才能评论

评论列表(0条)

保存