This code demonstrates how to use Heap Sort to prioritize high-risk zones based on their severity levels.
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
// Function to heapify a subtree rooted at index i
void heapify(vector<pair<int, int>> &zones, int n, int i) {
int largest = i; // Initialize largest as root
int left = 2 * i + 1;
int right = 2 * i + 2;
// Check if left child exists and is greater than root
if (left < n && zones[left].second > zones[largest].second)
largest = left;
// Check if right child exists and is greater than the largest so far
if (right < n && zones[right].second > zones[largest].second)
largest = right;
// If largest is not root
if (largest != i) {
swap(zones[i], zones[largest]); // Swap root with largest
heapify(zones, n, largest); // Recursively heapify the affected subtree
}
}
// Function to perform Heap Sort
void heapSort(vector<pair<int, int>> &zones) {
int n = zones.size();
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(zones, n, i);
// Extract elements from heap one by one
for (int i = n - 1; i >= 0; i--) {
// Move current root to end
swap(zones[0], zones[i]);
// Call max heapify on the reduced heap
heapify(zones, i, 0);
}
}
// Function to map severity levels to numerical values
int severityToValue(const string &severity) {
if (severity == "High")
return 3;
else if (severity == "Medium")
return 2;
else if (severity == "Low")
return 1;
return 0;
}
// Function to display zones
void displayZones(const vector<pair<int, int>> &zones) {
for (const auto &zone : zones) {
cout << "Zone " << zone.first << " - Severity: " << zone.second << endl;
}
cout << endl;
}
int main() {
// Example: Zones with their severity levels
vector<pair<int, string>> inputZones = {
{1, "Medium"},
{2, "High"},
{3, "Low"},
{4, "High"},
{5, "Medium"}};
// Convert severity levels to numerical values
vector<pair<int, int>> zones;
for (const auto &zone : inputZones) {
zones.push_back({zone.first, severityToValue(zone.second)});
}
cout << "Before Sorting:\n";
displayZones(zones);
// Sort the zones using Heap Sort
heapSort(zones);
cout << "After Sorting (High Priority First):\n";
displayZones(zones);
return 0;
}