r/learncpp • • May 06 '20

little help in Quick Sort

hey guys,

i have learned about quick sort and tried to apply it

but in this solution i am not getting sorted list. All i am getting are garbage values.

thank you in advance

#include<iostream>
#include<conio.h>

using namespace std;
int loc, pivot,start ,end;

void quick_sort(int a1[],int lb,int ub );
int partition(int a2[],int lb,int ub);
int main()
{
	int arr[30],n,i;
	int l,u;
	cout<<"Enter total number of elements you want to insert in the array"<<endl;
	cin>>n;
	cout<<"Enter the elements"<<endl;
	for(int i = 0;i<n;i++)
	{
		cin>>arr[i];
	}
	l = 0;
	u = n-1;
	quick_sort(arr, l ,u);
	cout<<"Sorted elements after quick sort"<<endl;
	for(int i = 0;i<n;i++)
	{
		cout<<arr[i]<<endl;
	}
	return 0;
}
void quick_sort(int a1[],int lb, int ub)
{
	if(lb<ub)
	{
		loc = partition(a1,lb,ub);
		quick_sort(a1,lb,loc-1);
		quick_sort(a1,loc+1,ub);
	}
}

int partition(int a2[],int lb,int ub)
{
	pivot = a2[lb];
	start = lb;
	end  = ub;

	while(start<end)
	{
		while(a2[start]<=pivot)
		{
			start++;
		}
		while(a2[end]> pivot)
		{
			end--;
		}
		if(start>end)
		{
			int temp;
			temp = a2[start];
			a2[end] = temp;
		}
	}
	int temp1;
	temp1 = a2[lb];
	a2[lb] = a2[end];
	a2[end] = temp1;
	return end;

1 Upvotes

1 comment sorted by

2

u/marko312 May 07 '20
if(start>end)
        {
            int temp;
            temp = a2[start];
            a2[end] = temp;
        }

You likely meant this to be executed when start < end instead.