讀書筆記 算法導(dǎo)論 快速排序 QuickSort 使用最后一個元素作為pivot
快速排序是實際編程應(yīng)用中最常見的排序方式
他有非常好的性能
最差情況的時間復(fù)雜度為 O(N平方)
平均情況的時間復(fù)雜度為 O(N logN) ,而且擁有一個非常小的系數(shù)
并且空間復(fù)雜度也非常小 就是O(N)
不過這個算法也是比較難理解的...
以下是一個使用最后一個元素作為pivot的快速算法實現(xiàn)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace IntroduceToAlgorithm
{
public class QuickSort
{
public void Sort(int[] A, int StartIndex = 1, int EndIndex = -1)
{
if (EndIndex == -1)
{
EndIndex = A.Length;
}
if (StartIndex < EndIndex)
{
int q = Partition(A, StartIndex, EndIndex);
Sort(A, StartIndex, q - 1);
Sort(A, q + 1, EndIndex);
}
}
public int Partition(int[] A, int StartIndex, int EndIndex)
{
int x = A[EndIndex - 1];
int i = StartIndex - 1;
for (int j = StartIndex; j <= EndIndex - 1; j++)
{
if (A[j - 1] <= x)
{
i = i + 1;
Exchange(A, i - 1, j - 1);
}
//A.Print();
}
Exchange(A, i, EndIndex - 1);
//A.Print();
return i + 1;
}
public void Exchange(int[] A, int i, int i2)
{
int val = A[i];
A[i] = A[i2];
A[i2] = val;
}
}
}
PS: 這算法在做實現(xiàn)的時候還是很難理解的...如果只是對著代碼看...雖然代碼很少
浙公網(wǎng)安備 33010602011771號