Code in C++
Description In this assignment you will implement two different algorithms for sorting elements in an array: Heap-Sort and Quick-Sort. In Quick-Sort, use a random element of the array as pivot.
Expert Answer
HeapSort.cpp
#include <iostream>
using namespace std;
void Heapify(int arr[], int uu, int no)
{
int qq, tempo;
tempo = arr[uu];
qq = 2*uu;
while (qq <= no)
{
if (qq < no && arr[qq+1] > arr[qq])
qq = qq+1;
if (tempo > arr[qq])
break;
else if (tempo <= arr[qq])
{
arr[qq/2] = arr[qq];
qq = 2*qq;
}
}
arr[qq/2] = tempo;
return;
}
void Heaping(int arr[], int no)
{
int uu, tempo;
for (uu = no; uu >= 2; uu–)
{
tempo = arr[uu];
arr[uu] = arr[1];
arr[1] = tempo;
Heapify(arr, 1, uu – 1);
}
}
void build_MaxHeapify(int arr[], int no)
{
int uu;
for(uu = no/2; uu >= 1; uu–)
Heapify(arr, uu, no);
}
int main()
{
int no, uu;
cout<<“nEnter the number of data element to be sorted: “;
cin>>no;
no++;
int arr[no];
for(uu = 1; uu < no; uu++)
{
cout<<“Enter element “<<uu<<“: “;
cin>>arr[uu];
}
build_MaxHeapify(arr, no-1);
Heaping(arr, no-1);
cout<<“nSorted Data “;
for (uu = 1; uu < no; uu++)
cout<<“->”<<arr[uu];
return 0;
}
Output:
QuickSort.cpp
#include <stdio.h>
#include <stdlib.h>
#define MAXIMUM 10
void rand_shuff(int x[])
{
srand(time(NULL));
int uu, qq, temporary;
for (uu = MAXIMUM – 1; uu > 0; uu–)
{
qq = rand()%(uu + 1);
temporary = x[uu];
x[uu] = x[qq];
x[qq] = temporary;
}
}
void swapping(int *x, int *b)
{
int temporary;
temporary = *x;
*x = *y;
*y = temporary;
}
int pivoting(int x[], int pio, int ran)
{
int pivotIndices = pio + rand()%(ran – pio + 1);
int pivots;
int uu = pio – 1;
int qq;
pivots = x[pivotIndices];
swapping(&x[pivotIndices], &x[ran]);
for (qq = pio; qq < ran; qq++)
{
if (x[qq] < pivots)
{
uu++;
swapping(&x[uu], &x[qq]);
}
}
swapping(&x[uu+1], &x[ran]);
return uu + 1;
}
void QuickSorting(int x[], int pio, int io)
{
int qq;
if (pio < io)
{
qq = pivoting(x, pio, io);
QuickSorting(x, pio, qq-1);
QuickSorting(x, qq+1, io);
}
}
int main()
{
int uu;
int x[MAXIMUM];
for (uu = 0; uu < MAXIMUM; uu++)
x[uu] = uu;
rand_shuff(x);
QuickSorting(x, 0, MAXIMUM-1);
for (uu = 0; uu < MAXIMUM; uu++)
printf(“%d n”, x[uu]);
return 0;
}
Output: