Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

//============================================================================ // Name : VectorSorting.cpp // Author : Your name // Version : 1.0 // Copyright : Copyright 2017 SNHU COCE // Description : Vector

//============================================================================ // Name : VectorSorting.cpp // Author : Your name // Version : 1.0 // Copyright : Copyright 2017 SNHU COCE // Description : Vector Sorting Algorithms //============================================================================

#include #include #include

#include "CSVparser.hpp"

using namespace std;

//============================================================================ // Global definitions visible to all methods and classes //============================================================================

// forward declarations double strToDouble(string str, char ch);

// define a structure to hold bid information struct Bid { string bidId; // unique identifier string title; string fund; double amount; Bid() { amount = 0.0; } };

//============================================================================ // Static methods used for testing //============================================================================

/** * Display the bid information to the console (std::out) * * @param bid struct containing the bid info */ void displayBid(Bid bid) { cout

/** * Prompt user for bid information using console (std::in) * * @return Bid struct containing the bid info */ Bid getBid() { Bid bid;

cout

cout

cout > bid.fund;

cout

return bid; }

/** * Load a CSV file containing bids into a container * * @param csvPath the path to the CSV file to load * @return a container holding all the bids read */ vector loadBids(string csvPath) { cout

// Define a vector data structure to hold a collection of bids. vector bids;

// initialize the CSV Parser using the given path csv::Parser file = csv::Parser(csvPath);

try { // loop to read rows of a CSV file for (int i = 0; i

// Create a data structure and add to the collection of bids Bid bid; bid.bidId = file[i][1]; bid.title = file[i][0]; bid.fund = file[i][8]; bid.amount = strToDouble(file[i][4], '$');

//cout

// push this bid to the end bids.push_back(bid); } } catch (csv::Error &e) { std::cerr

// FIXME (2a): Implement the quick sort logic over bid.title

/** * Partition the vector of bids into two parts, low and high * * @param bids Address of the vector instance to be partitioned * @param begin Beginning index to partition * @param end Ending index to partition */ int partition(vector& bids, int begin, int end) { //set low and high equal to begin and end

// pick the middle element as pivot point // while not done

// keep incrementing low index while bids[low]

/* If there are zero or one elements remaining, all bids are partitioned. Return high */ // else swap the low and high bids (built in vector method) // move low and high closer ++low, --high //return high; }

/** * Perform a quick sort on bid title * Average performance: O(n log(n)) * Worst case performance O(n^2)) * * @param bids address of the vector instance to be sorted * @param begin the beginning index to sort on * @param end the ending index to sort on */ void quickSort(vector& bids, int begin, int end) { //set mid equal to 0

/* Base case: If there are 1 or zero bids to sort, partition is already sorted otherwise if begin is greater than or equal to end then return*/

/* Partition bids into low and high such that midpoint is location of last element in low */ // recursively sort low partition (begin to mid)

// recursively sort high partition (mid+1 to end)

}

// FIXME (1a): Implement the selection sort logic over bid.title

/** * Perform a selection sort on bid title * Average performance: O(n^2)) * Worst case performance O(n^2)) * * @param bid address of the vector * instance to be sorted */ void selectionSort(vector& bids) { //define min as int (index of the current minimum bid)

// check size of bids vector // set size_t platform-neutral result equal to bid.size()

// pos is the position within bids that divides sorted/unsorted // for size_t pos = 0 and less than size -1 // set min = pos // loop over remaining elements to the right of position // if this element's title is less than minimum title // this element becomes the minimum // swap the current minimum with smaller one found // swap is a built in vector method }

/** * Simple C function to convert a string to a double * after stripping out unwanted char * * credit: http://stackoverflow.com/a/24875936 * * @param ch The character to strip out */ double strToDouble(string str, char ch) { str.erase(remove(str.begin(), str.end(), ch), str.end()); return atof(str.c_str()); }

/** * The one and only main() method */ int main(int argc, char* argv[]) {

// process command line arguments string csvPath; switch (argc) { case 2: csvPath = argv[1]; break; default: csvPath = "eBid_Monthly_Sales_Dec_2016.csv"; }

// Define a vector to hold all the bids vector bids;

// Define a timer variable clock_t ticks;

int choice = 0; while (choice != 9) { cout > choice;

switch (choice) {

case 1: // Initialize a timer variable before loading bids ticks = clock();

// Complete the method call to load the bids bids = loadBids(csvPath);

cout

// Calculate elapsed time and display result ticks = clock() - ticks; // current clock ticks minus starting clock ticks cout

break;

case 2: // Loop and display the bids read for (int i = 0; i

break;

// FIXME (1b): Invoke the selection sort and report timing results

// FIXME (2b): Invoke the quick sort and report timing results

} }

cout

return 0; } image text in transcribedimage text in transcribedimage text in transcribed

Overview The focus of these problems will be working with information extracted from a municipal government data feed containing bids submitted for auction of property. All materials for this assignment can be found in the Supporting Materials section below. The data set is provided in two comma-separated files: 1. eBid_Monthly_Sales.csv (larger set of 12,023 bids) 2. eBid_Monthly_Sales_Dec_2016.csv (smaller set of 76 bids) This assignment is designed to explore sorting algorithms by implementing both a selection sort and quicksort of a vector of bids loaded from a CSV file. We provide a starter console program that uses a menu to enable testing of the sort logic you will complete. It also allows you to pass in the path to the bids CSV file to be loaded, enabling you to try both files. In this version, the following menu is presented when the program is run: Menu: 1. Load Bids 2. Display All Bids 3. Selection Sort All Bids 4. QuickSort All Bids 9. Exit Enter choice: The VectorSorting.cpp program is partially completed. It contains empty methods representing the programming interface used to interact with the linked list. You will need to add logic to the methods to implement the necessary behavior. Here are the methods in VectorSorting.cpp that you must complete: void selectionsort(vector\& bids) void quicksort(vector\& bids, int begin, int end) int partition(vector\& bids, int begin, int end) Prompt You will need to perform the following steps to complete this activity: Setup: Begin by creating a new C++ project with a project type of "Hello World C++ Project". a. Name the project "VectorSorting". Remember to pick the correct compiler in Toolchains and click Finish. This will create a simple VectorSorting.cpp source file under the /src directory. b. Download the starter program files and copy them to the project's /src directory, replacing the existing auto-generated ones. Remember to right-click on the project in the Project Explorer pane on the left and Refresh the project so it adds all the new files to the src folder underneath. c. Because this activity uses C++11 features, you may need to add the std=c++11 compiler switch to the miscellaneous settings. Task 1: Implement the selection sort algorithm: a. Code the selection sort logic using "bid.title" as the sort field. b. Invoke the selectionSort() method from the main() method includigg collecting and reporting timing results. Task 2: Implement the quicksort algorithm: a. Code the quicksort logic using "bid.title" as the sort field. b. Invoke the quickSort() method from the main0) method including collecting and reporting timing results. Here is sample output from running the completed program: >./vectorsorting /Downloads/eBid_Monthly_Sales.csv > Vectorsorting.exe Downloads\eBid_Monthly_Sales.csv Loading bids from CSV and performing a selection sort: Loading bids from CSV and performing a quicksort: Note the dramatic difference in the time it takes to sort over 12,000 records - 10.6 seconds versus 4 hundredths of a second! Your assignment submission must address the following rubric criteria: - Code Reflection: A brief explanation of the code and its purpose, and a brief discussion of your experience in developing it, including any issues that you encountered while completing the exercise and what approaches you took to solve them - Pseudocode or Flowchart: A pseudocode or flowchart description of the code that is clear and understandable and captures accurate logic to translate to the programming language - Specifications and Correctness: Source code must meet its specifications and behave as desired. Correct code produces the correct output as defined by the data and problem; however, you should also produce fully functioning code (with no errors) that aligns with as many of the specifications as possible. You should write your code in such a way that the submitted file executes, even if it does not produce the correct output. You will be given credit for partially correct output that can be viewed and seen to be partially correct. - Annotation / Documentation: All code should also be well-commented. This is a practiced art that requires striking a balance between commenting everything, which adds a great deal of unneeded noise to the code, and commenting nothing. Well-annotated code requires you to: - Explain the purpose of lines or sections of your code, detailing the approach and method you took to achieve a specific task in the code. - Document any section of code that is producing errors or incorrect results. - Modular and Reusable: Programmers should develop code that is modular and reusable. If it contains functionality and responsibility in distinct methods, code is more flexible and maintainable. Your code should adhere to the single responsibility principle-classes and methods should do only one job. If you can replace a method with another that uses a different technique or implementation without impacting (having to refactor or rewrite) other parts of your code, then you have succeeded in creating modular methods. - Readability: Code needs to be readable to a knowledgeable programmer. In this course, readable code requires: - Consistent, appropriate whitespace (blank lines, spaces) and indentation to separate distinct parts of the code and operations - Explicit, consistent variable names, which should clearly indicate the data they hold and be formatted consistently: for example, numOrders (camelCase) or item_cost (underscored) - Organized structure and clear design that separates components with different responsibilities or grouping-related code into blocks Guidelines for Submission To complete this assignment, submit the CPP code files and a code reflection and associated pseudocode or flowchart written portion. Your written portion should be 1-2 paragraphs in length

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Object Databases The Essentials

Authors: Mary E. S. Loomis

1st Edition

020156341X, 978-0201563412

More Books

Students also viewed these Databases questions