简单的插入算法

来源:互联网 发布:紫峰软件中心 编辑:程序博客网 时间:2024/05/22 12:46
import java.util.*;
class Array6Insert 
{
public static void main(String[] args) 

{

               /*
简单的插入算法,


 在一组已经排好序的数组中, 插入一个数据,注意要插入到对应的位置

              */

          int[] scores = new int[6];


scores[0] = 20;
scores[1] = 15;
scores[2] = 22;
scores[3] = 67;
scores[4] = 33;

               //.对没有大小顺序的数组元素 进行升序排序

                Arrays.sort(scores);

                //.插入数据
//提示用户输入要插入的新数据

               System.out.println("请输入您要插入的数据:");
Scanner input = new Scanner(System.in);
int newNum = input.nextInt();

               //声明一个变量,来存储 这个新数据的索引位置

                int newIndex = scores.length -1;

              //找到这个新数据要插入的位置

               for (int i = 0; i < scores.length; i++)
{

                 if (newNum <= scores[i])
{

                         newIndex = i - 1;
break;
}

}
System.out.println(newIndex);

               // 从newIndex 开始整体把数组后移一个位置出来

               for (int index = 0; index < newIndex; index++)
{

                     scores[index] = scores[index + 1];
                }

                // 给挪出来的位置赋值
//加判断

                scores[newIndex] = newNum;



System.out.println("---------------------------------");

               // 循环遍历数组,看结果是多少

                 for (int value : scores)
{
System.out.println(value);
}





}
}

0 0