惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
V
Vulnerabilities – Threatpost
L
LINUX DO - 热门话题
H
Hacker News: Front Page
Hacker News - Newest:
Hacker News - Newest: "LLM"
L
Lohrmann on Cybersecurity
Cisco Talos Blog
Cisco Talos Blog
O
OpenAI News
S
Securelist
Security Latest
Security Latest
T
Threat Research - Cisco Blogs
H
Heimdal Security Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Recorded Future
Recorded Future
Microsoft Azure Blog
Microsoft Azure Blog
MyScale Blog
MyScale Blog
Webroot Blog
Webroot Blog
The Hacker News
The Hacker News
Google Online Security Blog
Google Online Security Blog
Latest news
Latest news
N
Netflix TechBlog - Medium
N
News and Events Feed by Topic
D
Docker
D
DataBreaches.Net
A
About on SuperTechFans
T
Tor Project blog
V
V2EX
G
Google Developers Blog
博客园 - Franky
N
News | PayPal Newsroom
T
The Blog of Author Tim Ferriss
I
InfoQ
H
Help Net Security
V2EX - 技术
V2EX - 技术
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
S
Security Affairs
SecWiki News
SecWiki News
The Register - Security
The Register - Security
人人都是产品经理
人人都是产品经理
NISL@THU
NISL@THU
小众软件
小众软件
B
Blog
T
Threatpost
P
Palo Alto Networks Blog
博客园 - 【当耐特】
L
LangChain Blog
AWS News Blog
AWS News Blog
月光博客
月光博客
宝玉的分享
宝玉的分享

jdhao's digital space

Conversion between base64 and OpenCV or PIL Image 腾讯云对象存储博客图床开启 CDN 加速(不需要购买额外域名) Search and Replace in Multiple Files in Vim/Neovim Change Table Column Width in LaTeX Image or Table Side by Side in LaTeX LaTeX 并排显示图像或表格 Firenvim: Neovim inside Your Browser Content inside HTML tags missing in Latest Hugo? Creating Markdown Front Matter with Ultisnips Labelme JSON 标注格式转 voc XML 格式 Nifty Nvim Techniques That Make My Life Easier -- Series 6 macOS 下如何为视频制作字幕 Running Command Asynchronously inside Neovim Resolving Merge Conflict after Git Stash Pop Pylint: command not found? A Hands-on Experience with Neovim's Built-in LSP Support How to Convert PDF to Images with Imagemagick 互联网上常用缩略语集锦 File Backup in Neovim Converting PDF Pages to Images with Poppler Nifty Nvim Techniques That Make My Life Easier -- Series 5 Neovim Configuration for System-wide Use How to sort a list of tuple or list in Python -- lambda or itemgetter? Building A Vim Statusline from Scratch 人类第一颗原子弹爆炸始末 Distributed Training in PyTorch with Horovod Learning Expect Programming Essential Knowledge about SSH Nifty LaTeX Techniques -- Series 1 更改 Adsense 邮寄地址,重新寄送 PIN Mintty Tips and Configurations Generating Table of Contents for Markdown with Tagbar Convert Python Script to Exe on Windows with Pyinstaller Ubuntu on Windows Missing after Windows Update 使用代理加速 Mac 终端下载速度 My Experience with Several Zsh Plugin Managers 深圳租房小记 How to Install zplug inside Docker Container Why don't settings inside bashrc or bash_profile take effect? Setting Up Locale in Linux 谷歌 Adsense 申请及在 Hugo 中的配置 How to Write Algorithm Pseudo Code in LaTeX Nifty Nvim Techniques That Make My Life Easier -- Series 4 A Few Grammar Questions in Writing How to Read and Write Images with Unicode Paths in OpenCV Creating A Professional Table in LaTeX with booktabs How to Create Proper Folding for Vim/Nvim Configuration Linux Tips and Tricks -- s1 JPEG Image Orientation and Exif How Do I Show the Current File Path In Neovim? JPEG Image Quality in PIL Difference between view, reshape, transpose and permute in PyTorch Convert PIL or OpenCV Image to Bytes without Saving to Disk Fast Movement and Navigation Inside Vim or Neovim Unintuitive Behaviour of Case Sensitivity in Python glob Binding Keys in Zsh 几把机械键盘试用体验 Nvim Autocompletion with Deoplete Converting Markdown to Beautiful PDF with Pandoc Exclusive and Inclusive Motion in Neovim/Vim Nifty Nvim Techniques Which Make My Life Easier -- Series 3 Why Doesn't Jedi Autocompletion Work for Some Methods Vim-like Editing inside Browser Markdown 生成 HTML 时汉字之间出现多余空格问题 小米 9 安装谷歌商店(Google Play Store)与相关配置 Create Mappings That Take A Count in Neovim Spell Checking in Nvim English Words Completion inside Neovim/Vim How to Use Python Inside Vim Script with Neovim Nifty Little Nvim Techniques to Make My Life Easier -- Series 2 Setting up Ultisnips for Neovim Mac 上罗技 M590 鼠标设置 Nifty Little Nvim Techniques to Make My Life Easier -- Series 1 A Complete Guide on Writing LaTeX with Vimtex in Neovim Manipulating Images with Alpha Channels in Pillow Sublime Text Regular Expression Cheat Sheet Cropping Rotated Rectangles from Image with OpenCV Boosting Your Productivity on Terminal with Zsh and Plugins 最新版 Rime 输入法使用 (2022 更新) Display Image with Pillow inside Ubuntu on Windows Faster Directory Navigation with z.lua Cmder Advanced Configurations Nvim-qt Settings on Windows 10 Tmux Plugin Install and Management How to Debug Python Code in Terminal Markdown Writing and Previewing in Neovim -- A Complete Guide Line Number Settings for More Efficient Movement in Neovim 两个大规模中文语料库介绍以及处理 Windows 系统下几款程序员不可不用的神器 我的 2018 阅读清单 A Complete Guide to Neovim Configuration for Python Development How Is Newline Handled in Python and Various Editors? Two Issues Related to ImageFont Module in PIL 在 Listary 中调用 GoldenDict 或欧路词典查单词 Reading and Writing Text Files on Windows The Mathematics behind Font Shapes --- Bézier Curves and More 快速识别图片字体:字体识别工具介绍 Deoplete Failed to Load at Startup after Updating Python neovim Package What Is The Difference between pip, pip3 and pip3.6 Shipped with Anaconda3? Windows 10 系统下 Neovim 安装与配置
快排(quick sort) C++ 实现
2021-07-10 · via jdhao's digital space

快排是一种快速排序算法,原理是从数组中选择一个 pivot,数组中小于等于 pivot 的元素放到左边,大于 pivot 的元素放到右边。然后对左边和右边数组分别递归进行快速排序,最后整个数组就成为排序好的数组。

非原地算法#

下面是 quicksort 的一种实现方法,非原地操作,每次会申请额外的空间存放左子数组和右子数组,但是理解上非常简单,没有任何难理解的地方:

#include <iostream>
#include <random>
#include <string>
#include <vector>
#include <ctime>

using std::random_device;
using std::cout;
using std::endl;
using std::vector;
using std::string;

void printList(vector<int>&, const string&);

vector<int> quickSort(vector<int> arr){
  if (arr.size() <= 1){
    return arr;
  }

  int N = arr.size();
  // arr[mid] 是 pivot
  int mid = (N-1) / 2;

  vector<int> left;
  vector<int> right;

  for (int i = 0; i < N; i++){
    if (i == mid) continue;

    // 对于原始数组,小于等于 pivot 的元素放左子数组,大于 pivot 的元素放右子数组
    if (arr[i] <= arr[mid]){
      left.push_back(arr[i]);
    }
    else{
      right.push_back(arr[i]);
    }
  }

  // 对左右子数组,再分别进行快排
  left = quickSort(left);
  right = quickSort(right);

  vector<int> new_arr;
  for (auto & x: left){
    new_arr.push_back(x);
  }
  new_arr.push_back(arr[mid]);
  for (auto & x: right){
    new_arr.push_back(x);
  }

  return new_arr;
}

// Generate a random sequence of length len, in range(low, high) (inclusive).
// need to #include<random>
vector<int> genRandom(int low, int high, int len){
  std::random_device rd;
  std::mt19937 gen(rd());
  std::uniform_int_distribution<int> distribution(low, high);

  vector<int> arr(len, 0);
  for (int i = 0; i != len; ++i){
      arr[i] = distribution(gen);
  }

  return arr;
}

void printList(vector<int>& arr, const string& desc){
  cout << desc << ": ";

  for (auto it = arr.begin(); it != arr.end(); it++){
    cout << *it << ((it != arr.end()-1) ? ' ' : '\n');
  }
}

int main()
{
  vector<int> arr = genRandom(1, 1000, 10);
  cout << "Before quick sort\n";
  printList(arr, "arr");

  auto arr1 = quickSort(arr);
  cout << "After quick sort\n";
  printList(arr1, "arr1");

  return 0;
}

快排实现一个坑,如果把数列中间元素作为 pivot,pivot 不能合并到左边的数组里面,否则会造成无限循环,pivot 必须单独拿出来。举个例子,假如数组为 arr = {2, 1}, pivot 是 arr[0],如果把小于等于 pivot 的元素放在左边数组,把大于 pivot 的元素放在右边数组,结果会是左边 {2, 1}, 右边 {}, 然后左右两边数组又调用 quickSort(),quickSort 终止条件是 arr.size() <= 1,左边的数组会继续重复上述的过程,永远循环下去。

正确的做法是把 pivot 单独拿出来,然后对左边数组进行 quickSort 递归,再对右边数组进行 quickSort 递归,然后把排序好的左数组,pivot,排序好的右数组合并起来。还以上面 case 为例,pivot 是 arr[0],左边数组 {1}, 右边数组 {}, 左右数组都达到终止条件返回,然后把左数组,pivot,右数组拼起来,排序好的数组就是 {1, 2}。

原地算法#

还有一种原地实现的算法,不需要开辟额外的空间,不过没有上面的实现那么直观容易理解。

#include <iostream>
#include <vector>
#include <random>

using namespace std;

// Generate a random sequence of length len, in range(low, high) (inclusive).
// need to #include<random>
vector<int> genRandom(int low, int high, int len){
  std::random_device rd;
  std::mt19937 gen(rd());
  std::uniform_int_distribution<int> distribution(low, high);

  vector<int> arr(len, 0);
  for (int i = 0; i != len; ++i){
      arr[i] = distribution(gen);
  }

  return arr;
}

int partion(vector<int> &arr, int low, int high) {
  int pivot = arr[low];
  int i = low;

  for (int j = low+1; j < high; j++){
    if (arr[j] <= pivot){
      i++;
      swap(arr[i], arr[j]);
    }
  }
  // 经过上述 for 循环, i 以及 i 左边都是小于等于 pivot 的元素,最后把 arr[i] 和
  // pivot 元素位置调换一下即可。即可保证我们完成了 partion
  swap(arr[i], arr[low]);

  return i;
}
void quickSort(vector<int>& arr, int low, int high){
  // low < high,才需要排序
  if (low < high){
    int r = partion(arr, low, high);

    quickSort(arr, low, r);
    quickSort(arr, r+1, high);
  }
}

int main() {
  vector<int> arr = genRandom(1, 100, 5);

   for(auto e: arr)
        cout<< e <<" ";
    cout<< endl;

  int N = arr.size();
  quickSort(arr, 0, N);

   for(auto e: arr)
        cout<< e <<" ";
    cout<< endl;

  return 0;
}

上述实现中,最核心的是 partion() 函数,partion 函数选择第一个元素作为 pivot,然后把 pivot 移动到最终它应该在的位置,并保证该位置左边都是小于等于 pivot 的元素,右边都是大于 pivot 的元素,最后返回 pivot 元素在新数组中的位置。pivot 不一定非要选择第一个元素,也可以选择最后一个元素,逻辑对应改动即可。其实 pivot 也可以选择其他元素,不过实现起来感觉比较麻烦,想了很久,也没实现对,总有一些 edge case 没处理正确。

参考#