heapsort.cxx 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. std::cout << "before sorting" << std::endl;
  34. sampleHeap.printArray();
  35. for (int i = n - 1; i >= 0; i--) {
  36. // insert heap.top into array A backwards to sort the array from min to max
  37. A[i] = sampleHeap.returnMax();
  38. // remove the max value from the heap
  39. sampleHeap.removeMax();
  40. std::cout << "after sorting" << std::endl;
  41. sampleHeap.printArray();
  42. }
  43. for (int j = 0; j <= n - 1; j++) {
  44. // adding values directly to JSON object
  45. topOfHeap.push_back(A[j]);
  46. std::cout << A[j] << ", ";
  47. }
  48. std::cout << std::endl;
  49. outputJSON[sampleName] = topOfHeap;
  50. }
  51. }
  52. std::cout << outputJSON << std::endl;
  53. // clean up memory
  54. file.close();
  55. sampleHeap.deleteHeap();
  56. return 0;
  57. }