风之语者

博客园 首页 新随笔 联系 订阅 管理

今天心血来潮,想到自己数据结构学的不好,于是查了下快速排序法的原理,实现了一个玩玩。算是对自身知识的补充。

View Code
public class Sort
{
/// <summary>
/// 快速排序法(ASC)
/// </summary>
/// <param name="SortInt"></param>
/// <param name="StartIndex"></param>
/// <param name="EndIndex"></param>
public static void FastSort(List<int> SortInt, int StartIndex, int EndIndex)
{
//如果结束索引小于或等于开始索引,说明排序粒度已经最小,只有一个数字了
if (EndIndex <= StartIndex)
{
return;
}
//初始比较值的索引
int intIndex = StartIndex;
//目标比较值的索引
int intTargetIndex = EndIndex;
//根据数组的宽度决定处理多少次
for (int intLoopCount = 0; intLoopCount <= EndIndex - StartIndex; intLoopCount++)
{
//初始比较值索引在目标比较值索引左边时,初始比较值比目标比较值大,交换一下值,将较小值放在初始比较值左边
if (SortInt[intIndex] > SortInt[intTargetIndex] && intIndex < intTargetIndex)
{
//交换值
int intTempValue = SortInt[intIndex];
SortInt[intIndex]
= SortInt[intTargetIndex];
SortInt[intTargetIndex]
= intTempValue;
//交换索引
int intTempIndex = intIndex;
intIndex
= intTargetIndex;
intTargetIndex
= intTempIndex;
}
//初始比较值索引在目标比较值索引右边时,初始比较值比目标比较值小,交换一下,较小值放在初始比较值左边
else if (SortInt[intIndex] < SortInt[intTargetIndex] && intIndex > intTargetIndex)
{
//交换值
int intTempValue = SortInt[intIndex];
SortInt[intIndex]
= SortInt[intTargetIndex];
SortInt[intTargetIndex]
= intTempValue;
//交换索引
int intTempIndex = intIndex;
intIndex
= intTargetIndex;
intTargetIndex
= intTempIndex;
}
//目标比较值索引向初始比较值索引靠拢
if (intIndex < intTargetIndex)
{
intTargetIndex
--;
}
else if (intIndex > intTargetIndex)
{
intTargetIndex
++;
}
else
{
continue;
}
}
int intLeftStartIndex = StartIndex;
int intLeftEndIndex = intIndex;
int intRightStartIndex = intIndex + 1;
int intRightEndIndex = EndIndex;
//将初始比较值左边的数组进行一次排序
FastSort(SortInt, intLeftStartIndex, intLeftEndIndex);
//将初始比较值右边的数组进行一次排序
FastSort(SortInt, intRightStartIndex, intRightEndIndex);
}
}

posted on 2011-07-05 17:45  风之语者  阅读(1358)  评论(3编辑  收藏  举报