Professional Documents
Culture Documents
Objective: - Build a Max-Heap Tree for any array. Analyze the operation in terms of running time
and find the time complexity of the algorithm.
Instruction: _
BUILD-MAX-HEAP (A)
1. n = length[A]
2. for i ← n/2 downto 1
3. do MAX-HEAPIFY(A, i, n)
MAX-HEAPIFY (A, i, n)
1. l ← LEFT(i)
2. r ← RIGHT(i)
3. if l ≤ n and A[l] > A[i]
4. then largest ←l
5. else largest ←i
6. if r ≤ n and A[r] > A[largest]
7. then largest ←r
8. if largest i
9. then exchange A[i] ↔ A[largest]
10. MAX-HEAPIFY(A, largest, n)
CODE:
#include <iostream>
using namespace std;
// Driver Code
int main()
{
int n;
cout<<"Enter the size of the array: ";
cin>>n;
int arr[n];
for(int i = 0; i <n; i++){
cin>>arr[i];
}
build_max_Heap(arr, n);
printHeap(arr, n);
return 0;
}
LAB EXERCISE-6
Objective: - Implement an algorithm for Heap sort (for increasing order of elements) for any
array. Analyze the operation in terms of running time and find the time complexity of the algorithm.
Instruction:-
HEAPSORT (A)
1. BUILD-MAX-HEAP(A)
2. for i ← length[A] downto 2
3. do exchange A[1] ↔ A[i]
4. MAX-HEAPIFY(A, 1, i - 1)
CODE:
#include <iostream>
using namespace std;
// Print an array
void printArray(int arr[], int n) {
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
cout << "\n";
}
// Driver code
int main() {
int n;
cout<<"Enter the size of the array: ";
cin>>n;
int arr[n];
cout<<"ENTER THE ARRAY ELEMENTS: ";
for(int i = 0; i <n; i++){
cin>>arr[i];
}
heapSort(arr, n);
COUNTING-SORT(A, B, n, k)
for i ← 0 to k
do C[i ] ← 0
for j ← 1 to n
do C[A[ j ]] ← C[A[ j ]] + 1
for i ← 1 to k
do C[i ] ← C[i ] + C[i − 1]
for j ← n downto 1
do B[C[A[ j ]]] ← A[ j ]
C[A[ j ]] ← C[A[ j ]] − 1
Do an example for A = 21, 51, 31, 01, 22, 32, 02, 33
Counting sort is stable (keys with same value appear in same order in output as they did in input) because
of how the last loop works.
CODE:
#include<iostream>
#include<algorithm>
using namespace std;
void display(int *array, int size) {
for(int i = 1; i<=size; i++)
cout << array[i] << " ";
cout << endl;
}
int getMax(int array[], int size) {
int max = array[1];
for(int i = 2; i<=size; i++) {
if(array[i] > max)
max = array[i];
}
return max;
}
void countSort(int *array, int size) {
int output[size+1];
int max = getMax(array, size);
int count[max+1];
for(int i = 0; i<=max; i++)
count[i] = 0;
for(int i = 1; i <=size; i++)
count[array[i]]++;
for(int i = 1; i<=max; i++)
count[i] += count[i-1];
for(int i = size; i>=1; i--) {
output[count[array[i]]] = array[i];
count[array[i]] -= 1;
}
for(int i = 1; i<=size; i++) {
array[i] = output[i];
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n+1]; //create an array with given number of elements
cout << "Enter elements:";
for(int i = 1; i<=n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
countSort(arr, n);
cout << "Array after Sorting: ";
display(arr, n);
}