quicksort算法

介绍 (Introduction)

Quicksort algorithm is one of the fastest internal sorting algorithms and today we are going to discuss this topic.

Quicksort算法是最快的内部排序算法之一,今天我们将讨论这个主题。

It is mainly based on the following three main strategies:

它主要基于以下三个主要策略:

  1. Split or Partition: Select a random element called pivot from the given sequence of elements to be sorted. Suppose the element is X, where X is any number. Now split the list into two small arrays or lists Y and Z such that, all elements in Y are smaller than X whereas all elements in Z are larger than X,拆分或分区 :从要排序的给定元素序列中选择一个随机元素,称为数据透视。 假设元素是X,其中X是任何数字。 现在将列表分成两个小数组或列表Y和Z,这样,Y中的所有元素都小于X,而Z中的所有元素都大于X,
  2. Sort the sub-arrays,排序子数组,
  3. Merge(join or concatenate) the sorted sub-arrays.合并合并或连接)已排序的子数组。

The split divides the arrays into two smaller arrays. When these sub-arrays are ultimately sorted recursively using quicksort these sub-arrays are called conquered. Therefore, quicksort is based on divide and conquer algorithm.

拆分将数组分成两个较小的数组。 当最终使用quicksort对这些子数组进行递归排序时,这些子数组称为conquered 。 因此,快速排序基于分而治之算法。

快速排序算法 (The Quick Sort Algorithm)

Suppose there are N elements as a[0], a[1], …, a[N-1]. The steps for using the quick sort algorithm are given below,

假设有N个元素,分别为a [0],a [1],…,a [N-1]。 下面给出了使用快速排序算法的步骤,

#1: Select any element as a pivot. For example, we select the first element here. It’ll help to split the array into two parts.

#1:选择任何元素作为枢轴 。 例如,我们在这里选择第一个元素。 这将有助于将数组分为两部分。


PIVOT = a[ FIRST ] //pivot selected,FIRST=0 here

#2: Initialize two pointers i and j as,

2:将两个指针ij初始化为


i = FIRST + 1 //First index of the array
j = LAST //Last index of array

#3: Now we increase the value of i until we locate an element that is greater than the pivot element,

3 :现在,我们增加i的值,直到找到一个大于数据透视元素的元素为止,


WHILE i<=j and a[i]<= PIVOTi=i+1

#4: We decrease the value of j until we find a value less than the pivot element,

4:我们减小j的值,直到找到小于枢轴元素的值,


WHILE j<=j and a[j]>= PIVOTj=j-1

#5: If i<j interchange a[i] and a[j].

#5:如果i <j,则互换a [i]和a [j]。

#6: Repeat Steps 2 to 4 until i>j,

6:重复步骤2到4,直到i> j

#7: Interchange the selected pivot and a[j],

#7:将所选的枢轴和a [j]互换,

#8: And finally recursively call this Quicksort for the two sub-arrays hence created at the two sides of the pivot element.

8 :最后为在枢轴元素两侧创建的两个子数组递归调用此Quicksort。

通过示例了解算法 (Understanding the Algorithm with an Example)

Now, let us understand how the algorithm works using a simple example.

现在,让我们使用一个简单的例子来了解算法的工作原理。

We have considered an array having values 50, 30, 10, 90, 80, 20, 40, 60 as shown in figure 1. At first, we select a pivot element which in our case is the first element, 50.

我们考虑具有如图1.在第一阵列值50,30,10,90,80,20,40,60中,我们选择一个枢轴元件,其在我们的例子中是第一要素,50。

Quicksort Algorithm
快速排序算法

Then we initialize i and j pointers as shown in figure 2 pointing on 30 and 60 respectively. Hence we move the i pointer towards the right until the element is greater than the pivot one. Which in our case we get at index 3, that is the value 90.

然后我们初始化ij指针,如图2所示,分别指向30和60。 因此,我们将i指针向右移动,直到元素大于枢轴元素。 在我们的情况下,我们得到的是索引3,即值90

Quicksort Algorithm
快速排序算法

Similarly, j is moved towards the left until it finds a value smaller than the pivot, which we get at index 6 that is a value of 40. At this point in figure 6, we can see we have got both i and j values. Finally, we swap the corresponding values and get to a position shown in figure 7.

类似地,j向左移动,直到找到小于枢轴的值,该值在索引6处为40 。 在图6的这一点上,我们可以看到我们同时获得了i和j值。 最后,我们交换相应的值并到达图7所示的位置。

Quicksort Algorithm
快速排序算法

Then we again go through the i and j index searching and hence get to figure 9, where both our pointers, i and j stand at 4th and 5th index.

然后,我们再次进行i和j索引搜索,从而转到图9 ,其中我们的指针i和j都位于第4和第5个索引。

Similar to the previous case, we swap the corresponding values at ith and jth positions. So after this, we need to move the pointer i towards the right and j towards the left. Since 20<50, so we need to increase i by 1 towards the right. As 80>50, we stop moving i further. As shown in figure 10 and 11.

与前面的情况类似,我们在ith和jth位置交换相应的值。 因此,在此之后,我们需要将指针i向右移动,将j向左移动。 由于20 <50,因此我们需要将i向右增加1。 随着80> 50,我们不再移动i。 如图1011所示

Quicksort Algorithm
快速排序算法

Then we start moving j towards the left. As 20<50, j is decreased by 1 and now stands at the 4th index as shown in figure 12. From the above condition, it is clear that i crosses j. Thus we stop at the point where j<i. Therefore the position of j is the split point.

然后我们开始将j向左移动。 当20 <50时,j减小1,现在位于第4个索引,如图12所示。从上述条件可以清楚地看出,i与j交叉。 因此,我们在j <i处停止。 因此,j的位置是分割点。

Hence we swap the pivot and the value at index j points at giving us the array as in figure 13.

因此,我们交换枢轴和索引j点的值,得到如图13所示的数组

Quicksort Algorithm
快速排序算法

After this, we have to apply the same method for the sub-arrays to the left and right of the pivot element, 50. By this divide and conquer method, finally, we will get our sorted array.

此后,我们必须在枢轴元素50的左侧和右侧对子数组应用相同的方法。 最后,通过这种分而治之的方法,我们将获得排序后的数组。

实现QuickSort算法 (Implementing the QuickSort Algorithm )

1. C语言中的QuickSort算法 (1. QuickSort Algorithm in C)


#include<stdio.h>
void quicksort(int a[25],int first,int last)
{int i, j, pivot, temp;if(first<last){pivot=first;i=first;j=last;while(i<j){while(a[i]<=a[pivot] && i<last)i++;while(a[j]>a[pivot])j--;if(i<j){temp=a[i];a[i]=a[j];a[j]=temp;}}temp=a[pivot];a[pivot]=a[j];a[j]=temp;quicksort(a,first,j-1);quicksort(a,j+1,last);}
}int main()
{int i, n, a[25];printf("Enter total no.of elements: ");scanf("%d",&n);printf("Enter the elements: ");for(i=0;i<n;i++)scanf("%d",&a[i]);quicksort(a,0,n-1);printf("Sorted Array: ");for(i=0;i<n;i++)printf(" %d",a[i]);return 0;
}

Output:

输出

Quicksort In C
C中的快速排序

2. Java中的QuickSort算法 (2. QuickSort Algorithm in Java)


public class Quicksort
{int position(int a[], int first, int last) { int pivot = a[last];  int i = (first-1); for (int j=first; j<last; j++) { if (a[j] <= pivot) { i++;  int temp = a[i]; a[i] = a[j]; a[j] = temp; } } int temp = a[i+1]; a[i+1] = a[last]; a[last] = temp; return i+1; } void Qsort(int a[], int first, int last) { if (first < last) { int p = position(a, first, last);  Qsort(a, first, p-1); Qsort(a, p+1, last); } } public static void main(String args[]) { int a[] = { 50, 30, 10, 90, 80, 20, 40, 60}; int n = a.length; Quicksort ob = new Quicksort(); ob.Qsort(a, 0, n-1); System.out.println("sorted array:"); for (int i=0; i<n; i++) System.out.print(a[i]+" "); System.out.println();}
}

Output

输出量

Quicksort In Java
Java快速排序

3. Python中的QuickSort算法 (3. QuickSort Algorithm in Python)


def quicksort(Mylist):n=len(Mylist)Rec_quicksort(Mylist, 0, n-1)def Rec_quicksort(Mylist, first, last):if first<last:pos=position(Mylist, first, last)Rec_quicksort(Mylist, first, pos-1)Rec_quicksort(Mylist, pos+1, last)def position(Mylist, first, last):pivot=Mylist[first]i=firstj=lastwhile i<j:while i<=j and Mylist[i]<=pivot:i=i+1while pivot<Mylist[j]:j=j-1if i<j:temp=Mylist[i]Mylist[i]=Mylist[j]Mylist[j]=temptemp=Mylist[first]Mylist[first]=Mylist[j]Mylist[j]=tempreturn jMylist=[ 50, 30, 10, 90, 80, 20, 40, 60 ]
print("Given list:",Mylist)quicksort(Mylist)
print("After sorting list is:",Mylist)

Output:

输出

Quicksort In Python
Python快速排序

QuickSort算法的时空复杂度 (Time and Space Complexity of QuickSort Algorithm)

空间复杂度 (Space complexity)

The space complexity of Quicksort algorithm is given by O(log(n)).

Quicksort算法的空间复杂度由O(log(n))给出。

时间复杂度 (Time complexity)

The time complexity of Quicksort algorithm is given by,

Quicksort算法的时间复杂度由下式给出:

  • O(n log(n)) for best case,O(n log(n))为最佳情况,
  • O(n log(n)) for the average case,O(n log(n))平均情况
  • And O(n^2) for the worst-case scenario.而O(n ^ 2)在最坏的情况下。

结论 (Conclusion)

Finally, we hope you have a very good understanding of the Quicksort algorithm. We implemented the same in C, Java, and Python to help programmers comfortable with either of the languages understand this algorithm better. Let us know if you have any questions about this topic in the comments.

最后,我们希望您对Quicksort算法有很好的了解。 我们用C,JavaPython实现了相同的功能以帮助程序员熟悉这两种语言,从而更好地理解该算法。 如果您在评论中对此主题有任何疑问,请告诉我们。

参考资料 (References)

  • https://en.wikipedia.org/wiki/Quicksorthttps://zh.wikipedia.org/wiki/Quicksort
  • https://www.journaldev.com/31541/merge-sort-algorithm-java-c-pythonhttps://www.journaldev.com/31541/merge-sort-algorithm-java-c-python
  • https://www.journaldev.com/784/sort-array-javahttps://www.journaldev.com/784/sort-array-java

翻译自: https://www.journaldev.com/37033/quicksort-algorithm-in-c-java-python

quicksort算法

quicksort算法_QuickSort算法–用C,Java,Python实现相关推荐

  1. python写界面c这算法_插入算法分别从C,java,python三种语言进行书写

    真正学懂计算机的人(不只是"编程匠")都对数学有相当的造诣,既能用科学家的严谨思维来求证,也能用工程师的务实手段来解决问题--而这种思维和手段的最佳演绎就是"算法&quo ...

  2. java python算法_用Python,Java和C ++示例解释的排序算法

    java python算法 什么是排序算法? (What is a Sorting Algorithm?) Sorting algorithms are a set of instructions t ...

  3. Twitter的分布式自增ID算法Snowflake实现分析及其Java、Php和Python版

    在分布式系统中,需要生成全局UID的场合还是比较多的,twitter的snowflake解决了这种需求,实现也还是很简单的,除去配置信息,核心代码就是毫秒级时间41位+机器ID 10位+毫秒内序列12 ...

  4. java python算法_用Java,Python和C ++示例解释的搜索算法

    java python算法 什么是搜索算法? (What is a Search Algorithm?) This kind of algorithm looks at the problem of ...

  5. 啊哈算法系列(C语言、python、Java )

    关于<啊哈!算法>相关资源 关于<啊哈!算法>相关资源 - 欣乐 - 博客园 第1章 一大波数正在靠近--排序 第1节 最快最简单的排序--桶排序 [坐在马桶上看算法]算法1: ...

  6. 刷题 BFS 广度优先算法 : 大胖子走迷宫 (python, java)

    刷题 BFS 广度优先算法 : 大胖子走迷宫 (python, java) https://www.lanqiao.cn/problems/234/learning/ http://lx.lanqia ...

  7. 集合70多种推荐算法,东北大学老师用Java写了一个开源库,在GitHub上收获近1500个Star...

     [AI科技大本营导读]在经过一年多的开发工作之后,LibRec 3.0 版本终于发布了.LibRec 是一个基于 Java 的开源算法工具库,覆盖了 70 余个各类型推荐算法,可以有效解决评分预测 ...

  8. 算法基础、算法比赛快速入门(java)

    想用Java快速入门算法?这篇文章你得看! 提示:本文章适合想要入门算法,并且想 "快速" 达到一定成果的同学们阅读~ 文章非常非常非常长(可能是你见过最长的算法基础篇章)!!! ...

  9. 中文分词算法python代码_中文分词算法之最大正向匹配算法(Python版)

    最大匹配算法是自然语言处理中的中文匹配算法中最基础的算法,分为正向和逆向,原理都是一样的. 正向最大匹配算法,故名思意,从左向右扫描寻找词的最大匹配. 首先我们可以规定一个词的最大长度,每次扫描的时候 ...

最新文章

  1. Python3 xml模块的增删改查
  2. Object:window_方法
  3. 未来AI将会在这10个方向升级|腾讯优图联合厦大发布趋势预测
  4. 服务器的攻与防(firewall 禁止指定Ip)
  5. java substance下载,做出漂亮的Java界面–substance.jar的使用 | 学步园
  6. Java Byte类的hashCode()方法及示例
  7. 跳石头(最小最大问题)
  8. MindManager的例图资源
  9. python使用lxml库对解析后的DOM树形成的xpath计算得到平均值、中位数、方差
  10. 【阿里技术】2019年开发者必读!20位阿里技术大牛们帮你列了一份经典书单!
  11. 【DirectX 9.0c入门教程】之一 开发环境搭建:安装vs2008 sp1和DirectX SDK
  12. 威密 android,勇士这赛季的结局,是否开始就已注定
  13. eclipse新建java项目隐藏了bin文件夹,只有src文件夹,解决方法
  14. 【Go实战基础】程序里面数据是如何显示到浏览器当中的
  15. 您的工厂生产精益了吗?-蔡颖先生首发于畅享网
  16. unixprocess+java+186_interproscan 的使用和遇到的问题
  17. 心跳之旅——iOS用手机摄像头检测心率(PPG)
  18. 章节三:BeautifulSoup
  19. 生物+化学 SY000 实验传闻记录 简述(暂记)
  20. HashSet集合保证元素唯一性原理分析

热门文章

  1. [转载] Python轻量Web框架Flask使用
  2. MATLAB获取系统时间
  3. Uncaught SyntaxError: Unexpected token export
  4. Codeforces 678E:Another Sith Tournament 状压DP
  5. 阻止默认事件event.preventDefault();
  6. poj 1703 并查集
  7. [BZOJ1602BZOJ1787BZOJ2144]树上LCA的算法巩固练习
  8. Java程序练习-Period
  9. Ubuntu学习日记--Lesson7:文件权限管理chmod
  10. 目标检测回归损失函数——IOU、GIOU、DIOU、CIOU、EIOU