From 4d2146759d705c49966968bbc5273ef3767bc914 Mon Sep 17 00:00:00 2001 From: Jidong Xiao Date: Mon, 9 Oct 2023 12:22:32 -0400 Subject: [PATCH] adding checkpoint 3 code --- labs/07_list_implementation/README.md | 9 +- labs/07_list_implementation/checkpoint3.cpp | 107 ++++++++++++++++++++ 2 files changed, 112 insertions(+), 4 deletions(-) create mode 100644 labs/07_list_implementation/checkpoint3.cpp diff --git a/labs/07_list_implementation/README.md b/labs/07_list_implementation/README.md index ab6e5cd..79a3238 100644 --- a/labs/07_list_implementation/README.md +++ b/labs/07_list_implementation/README.md @@ -44,11 +44,12 @@ Debugging a Merge Sort program. We expect our program [checkpoint3.cpp](checkpoi ```console $ g++ checkpoint3.cpp $ ./a.out -Test Case 1: Original Array: 5 2 9 1 5 6 -Sorted Array: 1 2 5 5 6 9 +Test Case 1: Original Vector: 5 2 9 1 5 6 +Sorted Vector: 1 2 5 5 6 9 + +Test Case 2: Original Vector: 3 8 2 7 4 +Sorted Vector: 2 3 4 7 8 -Test Case 2: Original Array: 3 8 2 7 4 -Sorted Array: 2 3 4 7 8 ``` But this program currently does not behave as expected. Please use a debugger to troubleshoot this program, find the problems and fix them. diff --git a/labs/07_list_implementation/checkpoint3.cpp b/labs/07_list_implementation/checkpoint3.cpp new file mode 100644 index 0000000..29177e4 --- /dev/null +++ b/labs/07_list_implementation/checkpoint3.cpp @@ -0,0 +1,107 @@ +#include +#include + +// prototype of the sorting function +std::vector sortVector(std::vector& nums); + +// function to print the elements of a vector +void printVector(const std::vector& nums) { + for (int num : nums) { + std::cout << num << " "; + } + std::cout << std::endl; +} + +int main() { + // test case 1 + std::vector test1 = {5, 2, 9, 1, 5, 6}; + std::vector result1 = sortVector(test1); + std::cout << "Test Case 1: Original Vector: "; + printVector(test1); + std::cout << "Sorted Vector: "; + printVector(result1); + std::cout << std::endl; + + // test case 2 + std::vector test2 = {3, 8, 2, 7, 4}; + std::vector result2 = sortVector(test2); + std::cout << "Test Case 2: Original Vector: "; + printVector(test2); + std::cout << "Sorted Vector: "; + printVector(result2); + std::cout << std::endl; + + return 0; +} + +// merge two vectors which are already sorted +std::vector& mergeVectors(std::vector& v1, std::vector& v2){ + int size1 = v1.size(); + int size2 = v2.size(); + std::vector v(size1+size2, 0); + int index1 = 0; + int index2 = 0; + int index = 0; + // traverse v1 and v2 at the same time + while(index1=size1){ + while(index2 sortVector(std::vector& nums) { + int size = nums.size(); + // base case + if(size==1){ + return nums; + } + // general case + // split the vector into two halves. + int mid = size/2; + + // nums1 to store the first half, and nums2 to store the second half. + std::vector nums1; + std::vector nums2; + + // copy the first half + for(int i=0;i