In: Computer Science
How would I add a quickSort function to the below C++ code to sort the randomly generated numbers?
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int i; int array[10]; int odd; int Max; int counter = 0; int main() { cout << "The 10 random elements are: "; cout << endl; srand ( time(0) ); for (int j = 0; j < 99; j++) { i = rand() % 100; if (i != i - 1) array[j] = i; else { i = rand() % 100; array[j] = i; } } for (int k = 0; k < 10 ; k++) { cout << array[k] << "\n"; } cout << endl; return 0; }
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int i;
int array[10];
int odd;
int Max;
int counter = 0;
int partition(int *a,int start,int end)
{
int pivot=a[end];
//P-index indicates the pivot value index
int P_index=start;
int i,t; //t is temporary variable
for(i=start;i<end;i++)
{
if(a[i]<=pivot)
{
t=a[i];
a[i]=a[P_index];
a[P_index]=t;
P_index++;
}
}
//Now exchanging value of
//pivot and P-index
t=a[end];
a[end]=a[P_index];
a[P_index]=t;
//at last returning the pivot value index
return P_index;
}
//function driver for quicksort
void quicksort_fun(int *a,int start,int end)
{
if(start<end)
{
int P_index=partition(a,start,end);
//from start to index
quicksort_fun(a,start,P_index-1);
//index to end
quicksort_fun(a,P_index+1,end);
}
}
int main()
{
cout << "The 10 random elements are: ";
cout << endl;
srand ( time(0) );
for (int j = 0; j < 99; j++)
{
i = rand() % 100;
if (i != i - 1)
array[j] = i;
else
{
i = rand() % 100;
array[j] = i;
}
}
cout<<"Before sorting : ";
for (int k = 0; k < 10 ; k++)
{
cout << array[k] << " ";
}
quicksort_fun(array,0,9);
cout<<"\nAfter sorting using quicksort: ";
for (int k = 0; k < 10 ; k++)
{
cout << array[k] << " ";
}
cout << endl;
return 0;
}