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

推荐订阅源

博客园 - 聂微东
GbyAI
GbyAI
S
SegmentFault 最新的问题
H
Hackread – Cybersecurity News, Data Breaches, AI and More
V
Visual Studio Blog
WordPress大学
WordPress大学
Hugging Face - Blog
Hugging Face - Blog
B
Blog
宝玉的分享
宝玉的分享
Last Week in AI
Last Week in AI
雷峰网
雷峰网
爱范儿
爱范儿
Vercel News
Vercel News
人人都是产品经理
人人都是产品经理
U
Unit 42
Microsoft Azure Blog
Microsoft Azure Blog
Microsoft Security Blog
Microsoft Security Blog
Jina AI
Jina AI
P
Proofpoint News Feed
A
About on SuperTechFans
I
InfoQ
F
Fortinet All Blogs
L
LangChain Blog
T
Tailwind CSS Blog

博客园 - John Rambo

定时关机脚本 Mean shift算法处理图像(Scilab & C#) Arimoto–Blahut algorithm (Mathematica) C#行列式计算程序 MIDL语法详解 (译) Virtual PC2007 + Redhat9下的网络配置 关于IFromatterProvider Total KMP 分析函数调用的汇编指令 why c++/cli About double-checked locking 对透明代理源码的一些理解 ReaderWriterLockSlim CallContext类 GDI+ is F**king unbelievable A better timer 第一个Postsharp插件 WeakReference System. ThreadStaticAttribute
1分钟搞定QuickSort算法
John Rambo · 2010-05-25 · via 博客园 - John Rambo

QuickSort是一种递归排序的算法,每一次迭代的过程是,

从序列中选出一个元素midvalue,把所有比它小的放在它的前面,大于等于它的放在它的后面。

然后再对前半个序列和后半个序列分别做同样的事。

参数start和endlist中要进行排序的子列的起始元素下标和结束元素下标。

以下实现中,一趟排序的过程为:

选第一个元素的值作为midvalue;

border是一个下标变量,意义是border右边的元素大于等于midvalue,此时border=1;

依次判断后面的所有元素,如果大于等于midvalue,就应当插入到border的右边,同时border+1;

当所有元素判断完后,是这么个情况:

[midvalue] [values < midvalue] [values >= than midvalue]

                     border->|

此时border是最后一个小于midvalue的元素的下标。

最后把第一个元素和border一交换,大功告成。

代码

static void Main(string[] args)
        {
            
//test1();
            
//List<int> li = new List<int>();
            
//li[18] = 99;
            
//test2();//int[] list = { 5, 4, 1, 3, 2, 7, 6 };
            
//int[] list = {6,5};
            
//int[] list = { 5,5,5};
            
//int[] list = {7,6,5,4,3,2,1 };
            
//int[] list = { 7,6,6,5,5,4,4,3,3,2,2,1,1};
            
//int[] list = { 6, 5, 1, 2, 7, 3, 6, 9, 8 };
            int[] list = new int[200];
            Random rand 
= new Random();
            
for (int i = 0; i < 200; i++)
            {
                list[i] 
= rand.Next(120);
            }
            QuickSort(list, 
0, list.Length - 1);

            Console.Read();

        }

private static void QuickSort(int[] list, int start, int end)
        {
            
if (start >= end) return;
            
int midvalue = list[start];//为了性能
            int border = start;//border右边是大于等于midvalue的第一个元素
            for (int i = start + 1; i <= end; i++)
            {
                
if (list[i] < midvalue) //需要放到border左边
                {
                    Swap(list, i, 
++border);
                }
            }
            Swap(list, border, start);
            QuickSort(list, start, border 
- 1);
            QuickSort(list, border 
+ 1, end);

        }

private static void Swap(int[] list, int i, int j)
        {
            
int temp = list[i];
            list[i] 
= list[j];
            list[j] 
= temp;
        }