Answer to Question #198045 in C++ for John

Question #198045

For this activity, you are required to provide les called sel.cpp as well as a make le to

compile and run it. In your le, sel.cpp, should have a skeleton of a main program as per

normal which you will then ll it in as per the following.

The objective of this activity is to demonstrate the selection sort algorithm for arrays.

Your program will need to read in from a le called list.txt. On each line, will be a

comma-delimited list of integer values. Each list will be 7 elements long. Your objective

is to sort each of these lists using the selection sort algorithm.

Each line should be sorted, and then displayed in sorted (ascending order with the small-

est element at the start of the string) one after the other. Each will be on a new line.

As a hint, implementing a function to do the selection sort itself will make the overall

program easier to implement.

For example:

Given a list: 6.4,3.25,7.5,2.5,1.1,11.6,0.5

The outcome of the sorting should be: 0.5,1.1,2.5,3.25,6.4,7.5,11.6


1
Expert's answer
2021-05-26T15:31:45-0400
#include <iostream> 
#include <fstream> 
#include <sstream>
#include <string>


using namespace std;
void selectionSort(float values[]) {
	int i, j, imin;
	for(i = 0; i<6; i++) {
		imin = i;  
		for(j = i+1; j<7; j++)
			if(values[j] < values[imin])
				imin = j;


		float temp;
		temp = values[i];
		values[i] = values[imin];
		values[imin] = temp;
	}
}


int main (){
	float values[7];
	//The file name
	const string FILE_NAME="list.txt";
	//Open the file
	ifstream ifstreamValuesFile;
	ifstreamValuesFile.open(FILE_NAME);
	string line;
	while (!ifstreamValuesFile.eof()){
		getline(ifstreamValuesFile,line);
		stringstream ss(line);
		int columns=0;
		while(ss.good())
		{
			//c++ split string by comma delimited
			string substr;
			getline(ss, substr,',');
			values[columns]=stof(substr);
			columns++;
		}
		selectionSort(values);
		for(int i=0;i<columns;i++){
			cout<<values[i]<<" ";
		}
		cout<<"\n";
	}
	//close files stream
	ifstreamValuesFile.close();

	system("pause");
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog