C# 常用排序算法



1, 快速排序:使用分冶思想,不断以某一元素为边界,分割成大小不同的区域。对于大多数数据集,这是最快的算法,除非分割成的区域每次都只有1个。算法复杂度:O(nLogn)

        public static void QuickSort(int[] ar, int begin, int end)
        {
            if (begin >= end)//1个或者无效区域
                return;
            if (end - begin == 1)
            {

            }

            int i = begin, j = end;

            int hole = (begin + end) / 2;
            int value = ar[hole];

            while (i <= j && (j > hole || i < hole))
            {
                while (j > hole && j >= i)
                {
                    if (ar[j] >= value)
                    {
                        j--;
                    }
                    else
                    {
                        ar[hole] = ar[j];
                        hole = j;
                        j--;
                    }

                }
                //Pt(ar);
                while (i < hole && i <= j)
                {
                    if (ar[i] <= value)
                    {
                        i++;
                    }
                    else
                    {
                        ar[hole] = ar[i];
                        hole = i;
                        i++;
                    }

                }
                //Pt(ar);
            }
            ar[hole] = value;
            //Pt(ar);
            if (hole - begin > 1)
            {
                QuickSort(ar, begin, hole - 1);
            }
            if (end - hole > 1)
            {
                QuickSort(ar, hole + 1, end);
            }
        }
QuickSort



2, 冒泡排序:思想简单的算法,平均算法复杂度:O(n^2)

        public static void BubbleSort(int[] ar)
        {
            bool isDoSorted = false;

            for (int i = 0; i < ar.Length; i++)
            {
                isDoSorted = false;
                for (int j = 0; j < (ar.Length - 1 - i); j++)
                {
                    if (ar[j] > ar[j + 1])
                    {
                        int temp = ar[j + 1];
                        ar[j + 1] = ar[j];
                        ar[j] = temp;
                        isDoSorted = true;
                    }
                }
                if (!isDoSorted)
                {
                    break;
                }
            }
        }

        public static void Pt(int[] ar)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("Arrary: ");
            foreach (int i in ar)
            {
                sb.Append(i.ToString() + ", ");
            }
            Console.WriteLine(sb.ToString());
        }

        public static int[] fillArr()
        {
            int[] ar = new int[1000];

            for (int i = 0; i < ar.Length; i++)
            {
                ar[i] = rd.Next(0, 99); //i;
            }

            return ar;
        }
BubbleSort

 

posted on 2014-07-08 09:56  Henry_Wang  阅读(389)  评论(0编辑  收藏  举报

导航