Question: StoogeSort | C++ Implementation The following code (provided largely by Chegg anonymous ) effectively reads in from data.txt integer values where the first value represents
StoogeSort | C++ Implementation
The following code (provided largely by Chegg anonymous) effectively reads in from "data.txt" integer values where the first value represents the length or degree of the array-to-be sorted. The last issue I have been struggling with is editing the code to accept multiple lines of input. A provided "data.txt" looks like this:
4 19 2 5 11 8 1 2 3 4 5 6 1 2 6 5 6 8 1 4 3 10 1 6 8 11 6 7 14 9 12 2 With the expected output to "stoogeOut.txt" of:
2 5 11 19 1 1 2 2 3 4 5 6 1 3 4 5 6 8 1 2 6 6 7 8 9 11 12 14
The following code only reads-out: 2 5 11 19
Thanks for your help!
#include
#include
#include
void StoogeSort(int A[], int start, int end)
{
//If the element in index 0 > element at end of array
if (A[end]
{
//Swap the elements at the beginning and the end
int temp = A[start];
A[start] = A[end];
A[end] = temp;
}
if (end - start + 1 > 2) //If there are more than 2 elements in array
{
int t = (end - start + 1) / 3;
StoogeSort(A, start, end - t); //StoogeSort the initial 2/3rd of the array
StoogeSort(A, start + t, end); //Stooge sort the last 2/3rd of the array
StoogeSort(A, start, end - t); //StoogeSort the initial 2/3rd of the array again
}
}
int main()
{
std::string input;
std::ifstream data("data.txt");
while (getline(data, input))
{
std::istringstream ss(input);
std::string token;
int n = 0;
getline(ss, token, ' ');
n = stoi(token); //First value read in defines array degree
std::cout
int A[n];
int index = 0;
while (getline(ss, token, ' '))
{
A[index++] = stoi(token); //Advance to next index, skipping first value
//std::cout
}
StoogeSort(A, 0, n - 1);
std::ofstream outfile;
outfile.open("stoogeOut.txt");
for (int i = 0; i
{
outfile
}
outfile
outfile.close();
}
return 0;
}

#include #include #include
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
