有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中。
有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中。
using System; namespace ConsoleTest2 { class Program { static void Main(string[] args) { const int n = 9; int[] a = { 0, 1, 2, 3, 5, 6, 7, 8, 9 }; //n=9 int[] b = new int[n + 1]; //n+1=10 int insertNumber = Int32.Parse(Console.ReadLine()); int index = 0, i = 0; for (;i < n; ++i) { if(a[i]>insertNumber) { index = i; break; } if (i == n - 1) index = n; } if(index==n) { for (i = 0; i < n; ++i) b[i] = a[i]; b[n] = insertNumber; } else if(index==0) { for (i = 1; i < n + 1; ++i) b[i] = a[i - 1]; b[0] = insertNumber; } else { for (i = 0; i < index; ++i) b[i] = a[i]; for (i = n - 1; i >= index; --i) b[i + 1] = a[i]; b[index] = insertNumber; } for(i=0;i<n+1;++i) { Console.Write("{0} ", b[i]); } Console.ReadKey(); } } }
using System; namespace ConsoleTest2 { class Program { static void Main(string[] args) { int[] a = { 12, 2, 8, 22, 16, 4, 10, 6, 14, 20 }; int n = 0; display(a, n); while(!process(a)) { ++n; display(a, n); } display(a, n+1); Console.WriteLine("count={0},result={1}", n+1, a[0]); Console.ReadKey(); } static bool process(int[] a) { int i = 0; int tmp = a[9]; int temp; for (; i < 10; ++i) { temp = a[i]; a[i] = a[i] / 2 + tmp / 2; tmp = temp; } for(i=0;i<10;++i) { if (a[i] % 2 == 1) a[i] += 1; } int j = 0; for(i=0;i<10;++i) { for(j=i+1;j<10;++j) { if (a[i] != a[j]) return false; } } return true; } static void display(int[] a,int cnt) { int i = 0; Console.Write("{0}>>>>>", cnt); for (; i < 10; ++i) Console.Write("{0} ", a[i]); Console.WriteLine(); } } }
[此贴子已经被作者于2016-5-4 17:29编辑过]