C work Make an instance variable for an integer array Take a
C++ work
Make an instance variable for an integer array.
Take an integer parameter that will be the number of elements in the array and create the array in the body.
Create a method called fill that will assign each element in your array a random integer between 0 and 9 (including 0 and 9). That means it must be in that range, not 1-9 or 2-10.
Create a method called print that will print out the contents of your array exactly as shown in the output below.
Create a method called sort that will sort the array in this fashion. You may NOT use any built in Java sorting functions.
Here is output for the Driver provided (results will vary due to the randomness of fill).
Solution
#include <iostream>
#include <stdlib.h>
using namespace std;
int partitionArray (int arr[], int start, int end)
{
int pivot = arr[end]; // pivot
int smaller = (start - 1); // Index of smaller element
int temp;
for (int j = start; j <= end- 1; j++)
{
if (arr[j] <= pivot)
{
smaller++;
temp = arr[smaller];
arr[smaller] = arr[j];
arr[j] = temp;
}
}
temp = arr[smaller+1];
arr[smaller+1] = arr[end];
arr[end] = temp;
return (smaller + 1);
}
void quickSort(int arr[], int start, int end)
{
if (start < end)
{
//Partition the array based on the partition function defined.
int partition_index = partitionArray(arr, start, end);
// Separately sort elements before
// partition and after partition
quickSort(arr, start, partition_index - 1);
quickSort(arr, partition_index + 1, end);
}
}
void fill(int *arr,int size)
{
int i;
for(i=0;i<size;i++)
*(arr+i) = rand()%10;
}
void printArray(int *arr,int size)
{
int i;
for(i=0;i<size;i++)
cout << *(arr+i) << \" \";
cout << endl;
}
int main() {
int *arr = new int[10];
int size = 10;
fill(arr,size);
cout << \"Array before sorting : \";
printArray(arr,size);
quickSort(arr,0,size-1);
cout << \"Array after sorting : \";
printArray(arr,size);
return 0;
}
OUTPUT:
Array before sorting : 3 6 7 5 3 5 6 2 9 1
Array after sorting : 1 2 3 3 5 5 6 6 7 9

