Hello,

I am trying to write the quick sort algorithm to take in an array of 20 random integers and sort them. However, it is producing weird output for the sorted list. My code is as follows, can anyone give me a little help here?

#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;

void q_sort(int list[], int left, int right);

void quicksort(int list[], int size)
{
  q_sort(list, 0, size - 1);
}


void q_sort(int list[], int left, int right)
{
	int pivot, l_hold, r_hold;
	l_hold = left;
	r_hold = right;
	pivot = list;

	while (left < right) {
		while ((list >= pivot) && (left < right)) {
			right--;
		}

		if (left != right) {
			list = list;
			left++;
		}

		while ((list <= pivot) && (left < right)) {
			left++;
		}

		if (left != right) {
			list = list;
			right--;
		}
	}

	list = pivot;
	pivot = left;
	left = l_hold;
	right = r_hold;

	if (left < pivot) {
		q_sort(list, left, pivot-1);
	}

	if (right > pivot) {
		q_sort(list, pivot+1, right);
	}
}

int main (void)
{
	int random[20];
	for (int i = 0; i < 20; i++) {
		//add 20 random numbers to array
		random[i] = rand();
		cout << random[i] << "\n";
	}
	cout << "\n";
	quicksort(random, 20);
	cout << random << "\n";
	return 0;
}

At least this is wrong:

list = pivot;

pivot is declared as an int and list is declared as an int array. You can't assign a single into to an array like that.

The same holds for these:
list >= pivot
list < = pivot
etc.

Um, by wierd output do you mean un sorted. Cause i have a strange feeling (unles si missed something) that you sort (or at least try to) the array list....which is just discarded once your sort is completed.

You need to pass by refrence... using the & operator in your function declartion for list.

Chris

a) you don't need to pass arrays "by reference" with the & in c++ because they are pass by reference by default.

b) 'cout << random << "\n";' on line 65 is your problem. outputting a whole array like that doesn't work. you need to output each element separately.

a) you don't need to pass arrays "by reference" with the & in c++ because they are pass by reference by default.

b) 'cout << random << "\n";' on line 65 is your problem. outputting a whole array like that doesn't work. you need to output each element separately.

oh jesus! I'm such a muppet. Thats 2 comment in 20 mins where i've said something completly stupid! I'm gonna get some sleep before i look like a complete idiot lol

Chris

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.