155-練習8 迴圈練習
阿新 • • 發佈:2018-11-17
8,有n(n<=100)個整數,已經按照從小到大順序排列好,現在另外給一個整數x,請將該數插入到序列中,並使新的序列仍然有序。輸出新的序列
int[] numArray = { 2, 4, 4, 6, 67, 785, 3244 }; int num = Convert.ToInt32(Console.ReadLine()); int[] numNew = new int[numArray.Length + 1]; int index = 0; bool isInsert = false; for (int i = 0; i < numNew.Length; i++) { if (i == numArray.Length && isInsert == false) { numNew[i] = num; isInsert = true; break; } if (num <= numArray[index] && isInsert == false) { numNew[i] = num; isInsert = true; } else { numNew[i] = numArray[index]; index++; } } for (int i = 0; i < numNew.Length; i++) { Console.Write(numNew[i] + " "); } Console.ReadKey();