快速排序(C#資料結構學習十)

來源:互聯網
上載者:User
using System;
using System.Collections.Generic;
using System.Text;

namespace SoloDataStructure
{
    class MyQuickSort
    {
        /**//// <summary>
        /// 快速排序演算法
        /// </summary>
        /// 快速排序為不穩定排序,時間複雜度O(nlog2n),為同數量級中最快的排序方法
        /// <param name="arr">劃分的數組</param>
        /// <param name="low">數組低端上標</param>
        /// <param name="high">數組高端下標</param>
        /// <returns></returns>
        static int Partition(int[] arr, int low, int high)
        {
            //進行一趟快速排序,返回中心軸記錄位置
           // arr[0] = arr[low];
            int pivot = arr[low];//把中心軸置於arr[0]
            while (low < high)
            {
                while(low<high && arr[high]>=pivot)
                --high;
            //將比中心軸記錄小的移到低端
            Swap(ref arr[high],ref arr[low]);
                while(low<high && arr[low]<=pivot)
                ++low;
            Swap(ref arr[high],ref arr[low]);
           //將比中心軸記錄大的移到高端
            }
            arr[low] = pivot; //中心軸移到正確位置
            return low;  //返回中心軸位置
        }
        static void Swap(ref int i, ref int j)
        {
            int t;
            t = i;
            i = j;
            j = t;
        } 
        static void QuickSort(int[] arr,int low,int high)
        {
            if (low < high-1)//當 arr[low,high]為空白或只一個記錄無需排序
            {
                int pivot = Partition(arr,low,high);
                QuickSort(arr,low,pivot-1);
                QuickSort(arr,pivot+1,high);

            }
        }
        static void Main(string[] args)
        {
            int[] arr=new int[]{54,62,99,14,28,1,8,77,99,3,110};
            QuickSort(arr, 0, arr.Length-1);
            Console.Write("Data After QuickSort:");
            foreach (int i in arr)
            {
                Console.Write(i+",");
            }
            Console.ReadLine();
        }
    }
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.