java 数组 插入算法

public class 插入算法 {
public static void main(String[] args) {
int [ ] musics = {12,23,89,77};
int [ ] newMusics =new int[musics.length+1];//新歌曲数组

    System.arraycopy(musics,0,newMusics,0,musics.length);
    Scanner sc=new Scanner(System.in);
    System.out.println("输入的歌曲名称:");
    int music = sc.nextInt();   //保存用户输入的歌曲名称

    int index = 0;
    for(int i = 0; i < 4; i++){
        //compareToIgnoreCase  正数 负数 0
        //源字符串大于目标字符串        正数
        if(musics[i]>music){
            index = i;
            break;
        }
    }
    //newMusics.length-1=4
    for(int i = 4; i > index; i--){
        newMusics[i] = newMusics[i-1];  
    }
    newMusics[index] = music;    

    System.out.println("新数组为:"+Arrays.toString(newMusics));



}

}

你可能感兴趣的:(java)