zoukankan      html  css  js  c++  java
  • 读书笔记 算法导论 快速排序 QuickSort 使用最后一个元素作为pivot

    快速排序是实际编程应用中最常见的排序方式

    他有非常好的性能

    最差情况的时间复杂度为 O(N平方)

    平均情况的时间复杂度为 O(N logN)  ,而且拥有一个非常小的系数

    并且空间复杂度也非常小 就是O(N)

    不过这个算法也是比较难理解的...

    以下是一个使用最后一个元素作为pivot的快速算法实现

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Runtime.InteropServices;

    namespace IntroduceToAlgorithm
    {

    public class QuickSort
    {
    public void Sort(int[] A, int StartIndex = 1, int EndIndex = -1)
    {
    if (EndIndex == -1)
    {
    EndIndex
    = A.Length;
    }
    if (StartIndex < EndIndex)
    {
    int q = Partition(A, StartIndex, EndIndex);

    Sort(A, StartIndex, q
    - 1);
    Sort(A, q
    + 1, EndIndex);
    }
    }

    public int Partition(int[] A, int StartIndex, int EndIndex)
    {
    int x = A[EndIndex - 1];
    int i = StartIndex - 1;

    for (int j = StartIndex; j <= EndIndex - 1; j++)
    {
    if (A[j - 1] <= x)
    {
    i
    = i + 1;
    Exchange(A, i
    - 1, j - 1);
    }
    //A.Print();
    }
    Exchange(A, i, EndIndex
    - 1);
    //A.Print();
    return i + 1;


    }

    public void Exchange(int[] A, int i, int i2)
    {
    int val = A[i];
    A[i]
    = A[i2];
    A[i2]
    = val;
    }
    }

    }

    PS: 这算法在做实现的时候还是很难理解的...如果只是对着代码看...虽然代码很少

  • 相关阅读:
    php数组到json的转变
    微信小程序获取微信绑定的手机号
    微信小程序授权登录
    用海豚框架(DolphinPHP)实现单/多图片上传时,如何获得图片路径
    数据库索引-简单了解
    php将二维数组转换成我想要的一维数组
    php的八大数据类型
    单例模式
    Springboot配置Sqlserver
    WinForm 文件操作
  • 原文地址:https://www.cnblogs.com/PurpleTide/p/2005984.html
Copyright © 2011-2022 走看看