1. 快速排序思想
2. 实现代码
3. 代码下载
1. 快速排序思想
快速排序主要是基于下面的事实:对于数组A,首先对其进行分割成两部分,前面一部分的值是小于所选定的主元(pivot),后面一部分是大于主元的,然后通过递归调用排序刚刚分割的两部分,即实现对与整个数组的排序。
伪代码如下:
2. 实现代码
using
System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Alice.Sort
{
public class QuickSort
{
// 实现快速排序[start, end]
public static void Sort( ref int [] arr, int start, int end)
{
// 循环结束条件
if (start >= end)
return ;
// 开始递归
int i = Partition( ref arr, start, end);
Sort( ref arr, start, (i - 1 ));
Sort( ref arr, (i + 1 ), end);
}
// 将[start,end]数组分割
public static int Partition( ref int [] arr, int start, int end)
{
// 选择主元,这里总是选择最后一个元素作为主元,或者这里
// 通过随机数随机选择主元
int pivot = arr[end];
int i = start - 1 ; // 游标i之前(<=i)应该全是小于pivot的元素
int tmp;
for ( int j = start; j <= end - 1 ; ++ j )
{
// 升序排列
if (arr[j] < pivot)
{
++ i;
// 交换两个元素arr[i]和arr[j]
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
// 将pivot(arr[end])的元素放置在(i + 1)的位置
tmp = arr[end];
arr[end] = arr[i + 1 ];
arr[i + 1 ] = tmp;
return (i + 1 );
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Alice.Sort
{
public class QuickSort
{
// 实现快速排序[start, end]
public static void Sort( ref int [] arr, int start, int end)
{
// 循环结束条件
if (start >= end)
return ;
// 开始递归
int i = Partition( ref arr, start, end);
Sort( ref arr, start, (i - 1 ));
Sort( ref arr, (i + 1 ), end);
}
// 将[start,end]数组分割
public static int Partition( ref int [] arr, int start, int end)
{
// 选择主元,这里总是选择最后一个元素作为主元,或者这里
// 通过随机数随机选择主元
int pivot = arr[end];
int i = start - 1 ; // 游标i之前(<=i)应该全是小于pivot的元素
int tmp;
for ( int j = start; j <= end - 1 ; ++ j )
{
// 升序排列
if (arr[j] < pivot)
{
++ i;
// 交换两个元素arr[i]和arr[j]
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
// 将pivot(arr[end])的元素放置在(i + 1)的位置
tmp = arr[end];
arr[end] = arr[i + 1 ];
arr[i + 1 ] = tmp;
return (i + 1 );
}
}
}
3. 代码下载