heapsort.cxx 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include <cstdio>
  2. #include <iostream>
  3. #include <string>
  4. #include <fstream>
  5. #include <sstream>
  6. #include "json.hpp"
  7. #include "priorityqueue.h"
  8. int main(int argc, char** argv) {
  9. // read JSON file and store in jsonObject
  10. std::ifstream file;
  11. file.open(argv[1]);
  12. nlohmann::json jsonObject;
  13. // Store the contents filename into jsonObject
  14. if (file.is_open()) {
  15. file >> jsonObject;
  16. }
  17. std::string sampleName; // Sample key name to iterate
  18. nlohmann::json outputJSON; // output JSON file
  19. int currValue = 0; // current key value
  20. int n = jsonObject["metadata"]["arraySize"];
  21. std::vector<int> A(n, 0);
  22. class PriorityQueue sampleHeap;
  23. sampleHeap.initiateHeap(n);
  24. for (auto itr = jsonObject.begin(); itr != jsonObject.end(); ++itr) {
  25. sampleName = itr.key();
  26. if (sampleName != "metadata") {
  27. nlohmann::json topOfHeap;
  28. for (auto arrayItr = jsonObject[sampleName].begin(); arrayItr != jsonObject[sampleName].end(); ++arrayItr) {
  29. // insert each array element into heap
  30. currValue = *arrayItr;
  31. sampleHeap.insert(currValue);
  32. }
  33. // insert heap top key values into an array backwards to sort from min to max
  34. for (int i = n - 1; i >= 0; i--) {
  35. A[i] = sampleHeap.returnMax();
  36. sampleHeap.removeMax();
  37. }
  38. // convert the new array into a JSON object
  39. for (int j = 0; j <= n - 1; j++) {
  40. // adding values directly to JSON object
  41. topOfHeap.push_back(A[j]);
  42. }
  43. outputJSON[sampleName] = topOfHeap;
  44. }
  45. }
  46. outputJSON["metadata"]["arraySize"] = n;
  47. outputJSON["metadata"]["numSamples"] = jsonObject["metadata"]["numSamples"];
  48. std::cout << outputJSON << std::endl;
  49. // clean up memory
  50. file.close();
  51. sampleHeap.deleteHeap();
  52. return 0;
  53. }