需要输出如下
原始数据是
{ 1,3,6,9,14,16,58,99};
请输入要插入的程序:2
{ 1,2,3,6,9,14,16,58};
插入的下标是1
原始数据是
{ 1,3,6,9,14,16,58,99};
要插入的 0
{ 0,1,3,6,9,14,16,58,};
下标是0
原始数据是
{ 1,3,6,9,14,16,58,99};
要插入的 100
{ 1,3,6,9,14,16,58,100};
下标是7
import java.util.Arrays;
public class Hello {
/**
* 在一组有序数中插入一个数
* @param ns 是一个组有序数
* @param value 需要插入到有序数中的数
*/
public static int insert(int[] ns, int value) {
int idx = 0;
for (int i = 0; i < ns.length; ++i) {
if (ns[i] >= value) { // 找到需要插入的位置
idx = i;
for (int j = ns.length - 1; j > i; --j) {
ns[j] = ns[j - 1];
}
ns[i] = value;
break;
}
}
return idx;
}
public static void main(String[] args) {
int[] ns = { 1,3,6,9,14,16,58,99};
int value = 2;
System.out.println("Before insert: " + Arrays.toString(ns));
int x = insert(ns, value);
System.out.println("After insert: " + Arrays.toString(ns) + " 位置" + x);
}
import java.util.Arrays;
import java.util.*;
class Hello {
/**
* 在一组有序数中插入一个数
* @param ns 是一个组有序数
* @param value 需要插入到有序数中的数
*/
public static int insert(int[] ns, int value) {
int idx = 0;
for (int i = 0; i < ns.length; ++i) {
if (ns[i] >= value) { // 找到需要插入的位置
idx = i;
for (int j = ns.length - 1; j > i; --j) {
ns[j] = ns[j - 1];
}
ns[i] = value;
break;
}
}
return idx;
}
public static void main(String[] args) {
int[] ns = { 1,3,6,9,14,16,58,99};
System.out.println("原始数据是:\n" + Arrays.toString(ns) + "\n请输入要插入的程序:");
Scanner scanner=new Scanner(System.in);
int value = scanner.nextInt();
int[] ns1 = ns;
ns = new int[ns1.length + 1];
for (int i = 0; i < ns1.length; i++) ns[i] = ns1[i];
int x = insert(ns, value);
System.out.println("After insert: " + Arrays.toString(ns) + "\n插入的下标是" + x);
}
}
输入2
输出
原始数据是:
[1, 3, 6, 9, 14, 16, 58, 99]
请输入要插入的程序:2
After insert: [1, 2, 3, 6, 9, 14, 16, 58, 99]
插入的下标是1
在线测试通过
List list = new List { 0, 5, 11, 45, 55, 61 };
int num = 21;
int current, next;
for (int i = 0; i < list.Count-1; i++)
{
current = list[i];
next = list[i + 1];
if (num>current&& num<next)
{
list.Insert(i+1,num);
}
}
有一种插入排序的算法正好可以解决你这种问题
设置了固定的数组个数
#include<stdio.h>
#define n 8
void main()
{
int a[n+1],x,j,i,k,temp1,temp2;
printf("请为数组升序输入%d个数据:\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("请输入待插入元素:\n");
scanf("%d",&x );
if (x>a[7])
{ a[8]=x; k=8;}
else
{
for (i=0;i<8;i++)
{
if (a[i]>x)
{
temp1=a[i]; a[i]=x; k=i;
for (j=i+1;j<11;j++)
{
temp2=a[j];
a[j]=temp1;
temp1=temp2;
}
break;
}
}
}
for (i=0;i<9;i++)
printf("排序后数组:%d ",a[i]);
printf("\n");
printf("位置:%d ",k);
}
一个插入排序就搞定了啊