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: 这算法在做实现的时候还是很难理解的...如果只是对着代码看...虽然代码很少

  • 相关阅读:
    Spring MVC的Controller统一异常处理:HandlerExceptionResolver
    Log4j按级别输出日志到不同文件配置
    Linux top命令用法
    free -m内存使用详解
    Linux运维中遇到的常见问题
    ubuntu16.04 nginx安装
    redis主从配置及主从切换
    Redis持久化配置-AOF
    如何处理消极想法
    libevent安装总结
  • 原文地址:https://www.cnblogs.com/PurpleTide/p/2005984.html
Copyright © 2011-2022 走看看