C ++快速排序程序

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值