Jump to content
  • Advertisement
Sign in to follow this  
Josheir

C++ Recursion Quick Sort

Recommended Posts

Edit : Maybe this should be in Beginners forum.  Sorry if it should be there.

 

 

 

Hello everyone, we're getting closer to the holidays.  Everyone have a safe happy season. 

 

I'm having trouble with a recursion problem for an : Inside the Quick Sort example.  At the very least, I am having trouble understanding how the right side of the quick sort is done after doing all the left hand subsections.  I understand that the partition function's job is to keep reducing the left-hand subsection.

I am not very good at recursion yet and I am also having trouble mostly with the two quicksort calls in the quicksort function.  

I could really use some help.  Thank you,

Josheir

 

Here is the code:

 

#include <iostream>
void getdata(int[], int);
void display(int[], int);
void swap(int &, int &);
void partition(int[], int&, int&);
void quicksort(int[], int, int);

//using std;
int main() {

	const int max = 10;
	int list[max];
	getdata(list, max);
	std::cout << "initial list\n";
	display(list, max);
	quicksort(list, 0, max - 1);
	std::cout << "sorted list:\n";
	display(list, max);

	while (1);

	return(0);
}


void getdata(int a[], int n)
{
	

	a[0] = 10;
	a[1] = 9;
	a[2] = 8;
	a[3] = 7;
	a[4] = 6;
	a[5] = 5;
	a[6] = 4;
	a[7] = 3;
	a[8] = 2;
	a[9] = 1;

}

void display(int a[], int n)
{

	for (int i = 0; i < n; i++)
		std::cout << a[i] << "[" << i << "]\t";

	std::cout << std::endl;


}
void swap(int &a, int &b)
{
	int temp = a; a = b; b = temp;
}

void quicksort(int a[], int left, int right)

{
	int l = left, r = right;

	

	
	partition(a, l, r);
	

	if (left < r)
	{
		
		quicksort(a, left, r);
		
	}

	


	if (l < right)
	{
		
		quicksort(a, l, right);
		


	}
}
void partition(int a[], int &l, int &r)
{

	

	

	int pivot = a[l];
	
	
	while (r > l)
	{
		while (a[l] < pivot)++l;
		while (pivot < a[r])--r;
		if (l > r)continue;
		swap(a[l], a[r]);
		++l; --r;

	}


	

}

 

Thanks again.

 
 
 
 
Edited by Josheir

Share this post


Link to post
Share on other sites
Advertisement

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!