I've this quicksort code, and it compiles. The thing is, I don't know how to give random values (integers) to the vector. The program should ask for the vector's size and then create the x random integers so it can apply the quiksort method.

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <stdlib.h>

using namespace std;

template <class T>
void quick_sort (vector<T> &v, int low, int high){

	//DO NOT SOLVE WHEN FACED WITH ONLY 1 OR 2 ELEMENTS
	if (low == high) {return;}
	else if (low + 1 == high){
		if (v[low] < v[high]){
			swap(v[low], v[high]);
		}
		return;
	}

	//PIVOTE
	int middle = (low + high)/2; 
	T pivot = v[middle]; 
	swap(v[middle], v[high]);

	//PARTITION
	int i, j;
	for (i = low; j = high-1; ;) {
		while (v[i] < pivot && i < j) i++;
		while (pivot < v[j] && i<j) j--;
		if (i<j) {swap(v[i], v[j]);}
		else {break;}
	}

	// PLACE PIVOTE IN CORRECT LOCATION
	if (i != high-1 && j!= high-1) {swap (v[i], v[high]);}

	//QUICKSORTE SUB-VECTROS
	if (i==low && j==low) {quick_sort(v, low+1, high);}
	else if (i==high-1 && j==high-1) {quick_sort(v, low, high-1);}
	else {quick_sort(v, low , i-1); quick_sort (v, i+1, high);}
}

An example:

#include <ctime>
#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

int getRandom(){ return rand() % 500; } 

int main(){
 srand(time(0)); //seed random number function
 int size = 0;
 cout << "Enter size: ";
 cin >> size;
 
 std::vector<int> data(size,0); // contains size number of 0's
  
 std::generate(data.begin(), data.end(), getRandom ); //fill vector with random numbers from [0,500)
}

Thanks a lot, this creates the vector right?
But how do I link it to the rest of my code. So the quick_sort takes the vector and works with it?
Thanks!

An example:

#include <ctime>
#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

int getRandom(){ return rand() % 500; } 

int main(){
 srand(time(0)); //seed random number function
 int size = 0;
 cout << "Enter size: ";
 cin >> size;
 
 std::vector<int> data(size,0); // contains size number of 0's
  
 std::generate(data.begin(), data.end(), getRandom ); //fill vector with random numbers from [0,500)
}

Thanks! And do you know how do I link it to the rest of my code. So the quick_sort takes the vector and works with it?
I'm trying to use this:

//.....
 std::vector<int> v(size,0); // contains size number of 0's
 std::generate (v.begin(), v.end(), getRandom); //fill vector with random numbers from [0,500)

quick_sort(v, 0, size-1);

But I just get errors.
Thanks!

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.