Here you will get program for quick sort in C++.
在这里,您将获得用于C ++ 快速排序的程序。
Quick Sort is one of the most efficient sorting algorithm whose best, worst and average case time complexities are O (n log n), O (n2) and O (n log n) respectively.
快速排序是最有效的排序算法之一,其最佳,最差和平均情况下的时间复杂度分别为O(n log n),O(n2)和O(n log n)。
How it works?
这个怎么运作?
1. We first pick a pivot element. There are various ways to pick a pivot element.
我们首先选择一个枢轴元素。 有多种选择枢轴元素的方法。
- Pick first element 选择第一个元素
- Pick last element 选择最后一个元素
- Pick a random element 选择一个随机元素
- Pick median element 选择中值元素
So we can use anyone of above methods to pick the pivot element. In the program given below I have picked first element as pivot.
因此,我们可以使用上述任何一种方法来选择枢轴元素。 在下面给出的程序中,我选择了第一个元素作为枢轴。
2. Now all the elements smaller than pivot are placed at its left while elements bigger are placed at right.
2.现在,所有小于枢轴的元素都放置在其左侧,而较大的元素放置在右侧。
3. Repeat the above two steps recursively for both half.
3.递归地重复以上两个步骤。
Below is the program to implement this algorithm in C++.
下面是在C ++中实现该算法的程序。
C ++快速排序程序 (Program for Quick Sort in C++)
#include <iostream>
using namespace std;
void quick_sort(int[],int,int);
int partition(int[],int,int);
int main()
{
int a[50],n,i;
cout<<"How many elements?";
cin>>n;
cout<<"\nEnter array elements:";
for(i=0;i<n;i++)
cin>>a[i];
quick_sort(a,0,n-1);
cout<<"\nArray after sorting:";
for(i=0;i<n;i++)
cout<<a[i]<<" ";
return 0;
}
void quick_sort(int a[],int l,int u)
{
int j;
if(l<u)
{
j=partition(a,l,u);
quick_sort(a,l,j-1);
quick_sort(a,j+1,u);
}
}
int partition(int a[],int l,int u)
{
int v,i,j,temp;
v=a[l];
i=l;
j=u+1;
do
{
do
i++;
while(a[i]<v&&i<=u);
do
j--;
while(v<a[j]);
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}while(i<j);
a[l]=a[j];
a[j]=v;
return(j);
}
Output
输出量
How many elements?6
有多少元素?6
Enter array elements:9 15 6 7 10 12
输入数组元素:9 15 6 7 10 12
Array after sorting:6 7 9 10 12 15
排序后的数组:6 7 9 10 12 15
翻译自: https://www.thecrazyprogrammer.com/2016/11/program-for-quick-sort-c.html