using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 快速排序
{
class QuickSort
{
private int q;
public void Sort(int[] A, int p, int r)
{
if (p < r)
{
q = Partion(A, p, r);
Sort(A, p, q - 1);
Sort(A, q + 1, r);
}
}
public int Partion(int[] A, int p, int r)
{
int x, i;
x = A[r];
i = p - 1;
for (int j = p; j <= r - 1; j++)
{
if (A[j] <= x)
{
i = i + 1;
//temp = A[i];
//A[i] = A[j];
//A[j] = temp;
this.Exchange(ref A[i], ref A[j]);
}
}
//temp = A[i + 1];
//A[i + 1] = A[r];
//A[r] = temp;
this.Exchange(ref A[i+1], ref A[r]);
return i + 1;
}
public void Exchange(ref int value1, ref int value2)
{
int temp;
temp = value1;
value1 = value2;
value2 = temp;
}
public void Display(int[] A)
{
foreach (int i in A)
{
Console.Write(i + " ");
}
}
}
class Program
{
static void Main(string[] args)
{
//int[] A = new int[] { 100, 2, 1, 6, 3, 99, 0, 78, 22 };
int[] A = new int[20];
Random r = new Random();
for (int i = 0; i < 20;i++ )
{
A[i] = r.Next(1,101);
}
QuickSort obj = new QuickSort();
Console.WriteLine("排序前的数列:");
obj.Display(A);
Console.WriteLine();
obj.Sort(A, 0, A.Length - 1);
Console.WriteLine("排序后的数列:");
foreach (int i in A)
{
Console.Write(i + " ");
}
Console.ReadKey();
}
}
}
时间复杂度:O(nlogn)