Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Program C++ Display in main the number of swaps. #include #include #include #include #define SIZE 4 //Number of Elements #define LIMIT 5 //Number Range #define

Program C++

Display in main the number of swaps.

#include #include #include #include #define SIZE 4 //Number of Elements #define LIMIT 5 //Number Range #define SWAP 0 using namespace std; // Swapping two values. void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } //ShuffleArray int ShuffleArray(int arr[], int n) { srand(time(NULL)); int sum = 0; for(int i = n-1; i > 0; i--){ int j = rand()%(i+1); swap(&arr[i], &arr[j]); } return n-1; }

// Partitioning the array on the basis of values at high as pivot value. int Partition(int a[], int low, int high) { int pivot, index, i; index = low; pivot = high; // Getting index of pivot. for(i=low; i < high; i++) { if(a[i] < a[pivot]) //ascending and desending { swap(&a[i], &a[index]); index++; } } // Swapping value at high and at the index obtained. swap(&a[pivot], &a[index]); return index; } // Random selection of pivot. int RandomPivotPartition(int a[], int low, int high) { int pvt, n, temp; n = rand(); // Randomizing the pivot value in the given subpart of array. pvt = low + n%(high-low+1); // Swapping pvt value from high, so pvt value will be taken as pivot while partitioning. swap(&a[high], &a[pvt]); return Partition(a, low, high); } // Implementing QuickSort algorithm. int QuickSort(int a[], int low, int high) { int pindex; if(low < high) { // Partitioning array using randomized pivot. pindex = RandomPivotPartition(a, low, high); // Recursively implementing QuickSort. QuickSort(a, low, pindex-1); QuickSort(a, pindex+1, high); } return 0; }

int main(int argc, char* argv[]) {

srand(time(NULL)); int arr[SIZE];

cout<<" Unsorted Data \t"; for (int i = 0; i < SIZE; ++i) { arr[i] = rand() % LIMIT +1; cout<< arr[i] << " "; }

ShuffleArray(arr, SIZE); cout << " Shuffled \t"; for (int i = 0; i < SIZE; i++){ cout<< arr[i] << " "; }

QuickSort(arr, 0, SIZE-1); // Printing the sorted data. cout<<" Sorted Array: "; for (int i = 0; i < SIZE; i++){ cout<< arr[i] << " "; } 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

Step: 3

blur-text-image

Ace Your Homework with AI

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

Get Started

Recommended Textbook for

Database Systems Design Implementation And Management

Authors: Peter Rob, Carlos Coronel

3rd Edition

0760049041, 978-0760049044

More Books

Students also viewed these Databases questions