c#实现冒泡、快速、选择和插入排序算法
2009-04-11 08:25:12 来源:WEB开发网其中low≤pivotpos≤high。(边界条件)
(2)求解:
通过递归调用快速排序对左、右子区间R[low..pivotpos-1]和R[pivotpos+1..high]快速排序。
(3)组合:
因为当"求解"步骤中的两个递归调用结束时,其左、右两个子区间已有序。对快速排序而言,"组合"步骤无须做什么,可看作是空操作。
using System;
namespace QuickSorter
{
public class QuickSort
{
public static void Sort(int[] numArr)
{
Sort(numArr, 0, numArr.Length - 1);
}
private static void Sort(int[] numArr, int left, int right)
{
if (left < right)
{
int middle = numArr[(left + right) / 2];
int i = left - 1;
int j = right + 1;
while (true)
{
while (numArr[++i] < middle) ;
while (numArr[--j] > middle) ;
if (i >= j)
break;
Swap(numArr, i, j);
}
Sort(numArr, left, i - 1);
Sort(numArr, j + 1, right);
}
}
private static void Swap(int[] numArr, int i, int j)
{
int number = numArr[i];
numArr[i] = numArr[j];
numArr[j] = number;
}
}
public class Program
{
static void Main(string[] args)
{
int[] arr = new int[] { 20, 41, 27, 14, 16, 1, 8, 55, 9, 35, 22, 14 };
QuickSort.Sort(arr);
Console.WriteLine("Numbers after quicksort:");
foreach (int i in arr)
{
Console.WriteLine(i);
}
Console.Read();
}
}
}
更多精彩
赞助商链接