zoukankan      html  css  js  c++  java
  • 快速排序法的C#实现

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

    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);
    }
    }

  • 相关阅读:
    Java数组的使用
    Java的栈堆以及数组两种不同类型的定义
    Java数组声明的创建
    JAVA递归
    Java可变参数
    Java方法(类--------对象--------方法)
    html块元素和内联元素的区别
    HTML基础介绍
    CSS网页美化元素属性介绍
    ArrayList类的remove(Object o)方法简述
  • 原文地址:https://www.cnblogs.com/WindBlog/p/2098519.html
Copyright © 2011-2022 走看看