快速排序 C/C++

2020-08-10 19:20发布

问题:

我的代码如下

#include<bits/stdc++.h>

using namespace std;

int number[100005];

void quicksort(int left, int right)
{
    if(left >= right)
    return;

    int i,j,key;
    i = left; 
    j = right;
    key = number[left];

    while(i != j)
    {
    while(number[j] >= key && i < j)
        j--;
    
    while(number[i] <= key && i < j)
        i++;
        
    if(i < j)
        swap(number[i], number[j]);

    }

    number[left] = number[i];    
    quicksort(left, i-1);
    quicksort(i+1, right);    
    
}

int main()
{
    int n;

    scanf("%d",&n);
    for(int i = 1; i <= n; i++)
    scanf("%d",&number[i]);

    quicksort(1, n);
    for(int i = 1; i <= n; i++)
    printf("%d ",number[i]);
    return 0;

}

以下为AC代码

#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math")
#include <bits/stdc++.h>

using namespace std;

void quick_sort(int nums[],int low,int high)
{
    if(low>=high)
    {
        return;
    }

    int l=low;
    int r=high;
    int tmp=nums[l];
    while(l<r)
    {
        while(nums[r]>tmp&&l<r)
            r--;
        
        while(nums[l]<=tmp&&l<r)    
            l++;
        
        if(l<r)
            swap(nums[l],nums[r]);
        
    }
    
    swap(nums[low],nums[r]);
    quick_sort(nums,low,l-1);
    quick_sort(nums,l+1,high);

}

int main()
{
    int n,a[100005];
        cin>>n;
    for(int i=0;i<n;++i)
        scanf("%d",a+i);

    random_shuffle(a,a+n);//随机乱序
    quick_sort(a,0,n-1);
    
    for(int i=0;i<n;++i)
        printf("%d ",a[i]);
    
    return 0;
}

想知道为什么我会有 3 个 TLE,好苦恼,求教!谢谢!

回答1:

请问AC代码中,随机乱序的作用是啥