快速排序(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();
}
}
}