The results:
The original values in array a:
The number of 1 is 19
The number of 2 is 6
The number of 3 is 7
The number of 4 is 12
The number of 5 is 4
The number of 6 is 13
The number of 7 is 20
The number of 8 is 11
The number of 9 is 11
The number of 10 is 3
The number of 11 is 15
The number of 12 is 11
The number of 13 is 13
The number of 14 is 10
The number of 15 is 8
The number of 16 is 2
The number of 17 is 2
The number of 18 is 10
The number of 19 is 10
The number of 20 is 20
The sorted values in array a:
The number of 1 is 2
The number of 2 is 2
The number of 3 is 3
The number of 4 is 4
The number of 5 is 6
The number of 6 is 7
The number of 7 is 8
The number of 8 is 10
The number of 9 is 10
The number of 10 is 10
The number of 11 is 11
The number of 12 is 11
The number of 13 is 11
The number of 14 is 12
The number of 15 is 13
The number of 16 is 13
The number of 17 is 15
The number of 18 is 19
The number of 19 is 20
The number of 20 is 20
The codes:
#include <iostream>
#define MAXN 20
#include <ctime>
#include <cstdlib>
void createArry(int a[]);
using namespace std;
void quickSort(int a[], int low, int high);
void printArray(int a[]);
int main()
{
srand((unsigned)time(NULL));
int a[MAXN];
createArry(a); //create an array randomly
cout << "The original values in array a:" <<endl;
printArray(a);
quickSort(a, 0, MAXN-1);
cout << "The sorted values in array a:" <<endl;
printArray(a);
return 0;
}
void createArry(int a[])
{
for(int i=0; i<MAXN; ++i){
a[i] = rand()%20 +1;
}
}
void quickSort(int a[], int low, int high)
{
int left_value = low;
int right_value = high;
if(low < high){
int pivot_position =0;
int pivot = a[low];
while(low < high){
while(low <high && a[high] >= pivot){
--high;
}
a[low] = a[high];
while(low <high && a[low] <= pivot){
++low;
}
a[high] = a[low];
}
a[low] = pivot;
pivot_position = low;
quickSort(a, left_value, pivot_position-1);
quickSort(a, pivot_position+1, right_value);
}else{
return;
}
}
void printArray(int a[])
{
int i;
for(i=0; i<MAXN; ++i){
cout<< "The number of " << i+1 << " is " << a[i]<< endl;
}
}