AlgorithmA.cxx 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // ShellSort implementation adapted from:
  2. // https://www.geeksforgeeks.org/shellsort/
  3. // Note: This code is used to illustrate the utility of automated testing
  4. // for verification purposes, so it may not function correctly. This is
  5. // intentional.
  6. #include <algorithm>
  7. #include <fstream>
  8. #include <iostream>
  9. #include <vector>
  10. #include "json.hpp"
  11. /* function to sort arr using shellSort */
  12. int shellSort(int arr[], int n)
  13. {
  14. // Start with a big gap, then reduce the gap
  15. for (int gap = n/2; gap > 0; gap /= 2)
  16. {
  17. // Do a gapped insertion sort for this gap size.
  18. // The first gap elements a[0..gap-1] are already in gapped order
  19. // keep adding one more element until the entire array is
  20. // gap sorted
  21. for (int i = gap; i < n - 1; i += 1)
  22. {
  23. // add a[i] to the elements that have been gap sorted
  24. // save a[i] in temp and make a hole at position i
  25. int temp = arr[i];
  26. // shift earlier gap-sorted elements up until the correct
  27. // location for a[i] is found
  28. int j;
  29. for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
  30. arr[j] = arr[j - gap];
  31. // put temp (the original a[i]) in its correct location
  32. arr[j] = temp;
  33. }
  34. }
  35. return 0;
  36. }
  37. // Driver program to test above function
  38. int main(int argc, char** argv)
  39. {
  40. if (argc != 2) {
  41. printf("Usage: %s inputFile\n", argv[0]);
  42. return EXIT_FAILURE;
  43. }
  44. // Get samples
  45. std::string inputFilename(argv[1]);
  46. std::ifstream inputFile;
  47. inputFile.open(inputFilename.c_str());
  48. nlohmann::json samples;
  49. if (inputFile.is_open()) {
  50. inputFile >> samples;
  51. } else {
  52. printf("Unable to open file %s\n", inputFilename.c_str());
  53. return EXIT_FAILURE;
  54. }
  55. int n = samples["metadata"]["arraySize"];
  56. int* sampleData = (int*) malloc(sizeof(int) * n);
  57. nlohmann::json result;
  58. result["metadata"] = samples["metadata"];
  59. for (auto itr = samples.begin(); itr != samples.end(); ++itr) {
  60. if (itr.key() != "metadata") {
  61. auto sample = itr.value();
  62. // InsertionSort
  63. std::copy(sample.begin(), sample.end(), sampleData);
  64. shellSort(sampleData, n);
  65. for (int i = 0; i < n; i++) {
  66. result[itr.key()].push_back(sampleData[i]);
  67. }
  68. }
  69. }
  70. std::cout << result << '\n';
  71. }