For this activity, you are required to provide les called sel.cpp as well as a makele 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
#include <iostream>
#include <fstream>
using namespace std;
void sort(double *a, int size);
int main()
{
ifstream fin;
fin.open("list.txt");
double A[7];
while(!fin.eof())
{
cout << "Initial array: ";
for(int i = 0; i < 7; i++)
{
fin >> A[i];
fin.ignore(1);
if(i == 6)
{
cout << A[i] << endl;
break;
}
cout << A[i] << ",";
}
sort(A, 7);
cout << "Sorted array: ";
for(int i = 0; i < 7; i++)
{
if(i == 6)
{
cout << A[i] << endl;
break;
}
cout << A[i] << ",";
}
}
return 0;
}
void sort(double *a, int size)
{
for(int i = 0; i < size - 1; i++)
{
int min = i;
{
for(int j = min + 1; j < size; j++)
{
if(a[j] < a[min]);
min = j;
}
}
double temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}
Comments
Leave a comment