I have 2 code of quick sort

#include <bits/stdc++.h>
using namespace std;
long long int partition(long long int a[],long long int be,long long int end)
{
srand(time(NULL));

//taking pivot as random element of the array use inbuilt rand function 

//generating a random number between beginning and ending index
int pivotIndex = be + rand() % (end - be+1);
int pivot;
pivot = a[pivotIndex];

swap(a[pivotIndex], a[end]);
pivotIndex = end;
int k = be - 1;
for (int i = be; i <end; i++)
{
    if (a[i] <= pivot)
    {
        k++;
        swap(a[i], a[k]);
    }
}
swap(a[k + 1], a[pivotIndex]);
return (k + 1);

}

// function for quick sort
void quicksort(long long int a[],long long int be,long long int end)
{
if (be < end)
{
long long int p = partition(a, be, end);
quicksort(a, be, p-1);
quicksort(a, p + 1, end);
}
}

main()
{
long long int n;
cin>>n;
long long int arr[n];
for(long long int i=0;i<n;i++)
cin>>arr[i];
quicksort(arr,0,n-1);
for(long long int i=0;i<n;i++)
{
cout<<arr[i];
}
}

#include <bits/stdc++.h>
using namespace std;

long long int partition(long long int arr[],long long int l,long long int r)
{
long long int j=0;
for(long long int i=0;i<r;i++)
{
if(arr[i]<arr[r])
{
swap(arr[i],arr[j]);
j++;
}
}
swap(arr[j],arr[r]);
return j;
}

void quick(long long int arr[],long long int i,long long int j)
{
if(i>=j)
return;
long long int pi=partition(arr,i,j);
quick(arr,i,pi-1);
quick(arr,pi+1,j);
}

main()
{
long long int n;
cin>>n;
long long int arr[n];
for(long long int i=0;i<n;i++)
cin>>arr[i];
quick(arr,0,n-1);
for(long long int i=0;i<n;i++)
cout<<arr[i]<<" ";
}

The second one is shown slower than the first one I can’t undderstand why

@Mehul7349
The reason is actually quite interesting
So in the first case where you take random pivot, you can expect it to divide the array in two somewhat equal halves each time
However, in the second case it will fail to work in dividing array equally in 2 halves like in case of decreasing, increasing and same elements in subarray

If your doubt is resolved please mark it as closed.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

No there is no problem in case of increasing or decreasing order it is working

@Mehul7349
I’m not saying it won’t work
It is a sorting algo it will obviously work
Issue with it is time complexity of N^2 in worst case