首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

求排序写法改善

2013-12-30 
求排序写法改进 对一组字符串中的数字进行大小排序,如下方法得到了正确的结果。private void butok_Click(o

求排序写法改进


 对一组字符串中的数字进行大小排序,如下方法得到了正确的结果。


          private void butok_Click(object sender, EventArgs e)
        {
          string str="8 9 3 16 10 10 8 6 10 12";
          string strTemp = "";
          string[] Arr = arrayList(str);
          for (int i = 0; i < Arr.Length; i++)
          {
              strTemp = strTemp + Arr[i].ToString() + " ";
          }
          strTemp = strTemp.Substring(0, strTemp.Length - 1);
          textBox1.Text = strTemp;
        }


        private string[] arrayList(string strTemp)
        {
            string[] a = strTemp.Split(' ');
            string temp;
            for (int i = 0; i < a.Length; i++)
            {
                for (int j = i + 1; j < a.Length; j++)
                {
                    if (Convert.ToDouble(a[i]) > Convert.ToDouble(a[j]))
                    {
                        temp = a[i];
                        a[i] = a[j];
                        a[j] = temp;
                    }
                }
            }
            return a;

        }




string str="8 9 3 16 10 10 8 6 10 12";
经过运算结果为
strTemp=“3 6 8 8 9 10 10 10 12 16”

求大神对方法进行一些改进,要求得出排序后原始值所在的位置,例如,3在原始字符串中排在第3的位置,6排在第8的位置。

最好能得到返回如下字符串strTemp=“(3:2) (6:7) (8:0) 8.. 9.. 10.. 10.. 10.. 12.. 16..”
能标识出每一个数字经过排序后,显示它在原始字符串中的位置。

[解决办法]

    class Program
    {
        static void Main(string[] args)
        {
            string str = "8 9 3 16 10 10 8 6 10 12";
            string[] arr = str.Split(' ');
            IndexNum[] arrIndexNum = new IndexNum[arr.Length];
            for (int i = 0; i < arrIndexNum.Length; i++)
            {
                arrIndexNum[i] = new IndexNum() { iIndex = i, iValue = Convert.ToDouble(arr[i]) };


            }

            var order = arrIndexNum.OrderBy(indexNum => indexNum.iValue).Select(indexNum=>string.Format("({0}:{1})", indexNum.iValue,indexNum.iIndex));
            Console.WriteLine(string.Join("", order));
            Console.ReadLine();
        }
    }

    public class IndexNum
    {
        public int iIndex;
        public double iValue;
    }

热点排行