冒泡排序

一直都知道冒泡排序的原理,但从未自己写过,觉得有必要亲自实现一次

 public string Sorter(string s)
        {
            string[] target = s.Split(',');
            int TheLength=target.Length;
            int[] result = new int[TheLength];
            result = ToInt(target);            
            while (true)
            {
                bool isfinished = true;
                for (int i = 0; i < target.Length-1; i++)
                {
                    if (result[i] > result[i + 1])
                    {
                        int temp = result[i + 1];
                        result[i + 1] = result[i];
                        result[i] = temp;
                        isfinished = false;
                    }
                }
                if (isfinished)
                {
                    break;
                }
            }            
            return string.Join(",", result);
        }

最外层while循环加个标志位判断排序是否完成,完成就break

下面写的是string数组转int数组的方法

 public int[] ToInt(string[] s)
        {
            int[] a = new int[s.Length];
            for (int i=0;i<s.Length;i++)
            {
                a[i] = int.Parse(s[i]);
            }
            return a;
        }

运行结果:

 

posted @ 2016-07-06 00:08  FOXCELL  阅读(127)  评论(0)    收藏  举报