Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

How to change this code to Quicksort. It is in merge sort...Thanks in advance. #include #include #include #define RAN_MAX 327 using namespace std; //functions void

How to change this code to Quicksort. It is in merge sort...Thanks in advance.

#include

#include

#include

#define RAN_MAX 327

using namespace std;

//functions

void mergeSort(vector v, int p, int q, int r);

void merge(vector v, int p, int r);

vector vector_get(int n)

{

int i;

int d;

vector v;

for (i = 0; i < n; ++i)

{

//cout << "Enter value " << i + 1 << ": ";

//cin >> d;

v.push_back(rand()%RAN_MAX);

}

return v;

}

//prints a vector

void vector_print(vector v)

{

size_t i;

for (i = 0; i < v.size() - 1 && i <10; ++i)

{

cout << v[i] << ", ";

}

cout << v[i] << endl;

}

void merge(vector &v, int p, int q, int r) {

int j, i;

int k = 0;

int n1 = q - p + 1;

int n2 = r - q;

/* create 2 arrays */

int L[n1+1], R[n2+1];

// Copy data to temp arrays L[] and R[]

for (i = 0; i < n1; i++)

L[i] = v[p + i];

for (j = 0; j < n2; j++)

R[j] = v[q +1 + j];

i = j = 0;

k = p;

//merge arrays to onw

while (i < n1 && j < n2)

{

if (L[i] <= R[j])

{

v[k] = L[i];

i++;

}

else

{

v[k] = R[j];

j++;

}

k++;

}

while (i < n1)

{

v[k] = L[i];

i++;

k++;

}

while (j < n2)

{

v[k] = R[j];

j++;

k++;

}

}

void mergeSort(vector &v, int p, int r) {

int q;//middle

if (p < r) {

q = (p + r) / 2;

mergeSort(v, p, q);

mergeSort(v, q + 1, r);

merge(v, p, q, r);

}

}

int main()

{

//declare variables

int n,p = 0,r;

vector a;

//ask user how many values they want to enter

cout << "Please enter how many values would you like to enter?: ";

cin >> n;

//get elements for vector a

a = vector_get(n);

//print vector a

cout << "unsorted,the first 10 values are : "<

vector_print(a);

//print sorted vector a

cout << "sorted,the first 10 values are : "<

r = a.size()-1;

mergeSort(a,p,r);

vector_print(a);

//main returns 0 upon successful completion

return 0;

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions

Question

3. Evaluate a Web-based training site.

Answered: 1 week ago