C++ sort array can somebody help me how to wirte the sortArray function #include
ID: 639890 • Letter: C
Question
C++ sort array
can somebody help me how to wirte the sortArray function
#include <iostream>
#include <string>
using namespace::std;
// function will display on cout the contents of an arrary - FUNCTION 1
void printArray(ostream & out, const string data[], int cellsUsed);
// function will sort an array - FUNCTION 2
void sortArray(string data[], int cellsUsed);
// NOTE: in the string class the assignment operator and all of the relational operators
// have been overloaded
// Thus, in your sort algorithm you can use data[i] < data[j]
void main()
{
const int CELLS = 5;
string names[CELLS] = { "tom", "mary", "ann", "bill", "carol" };
cout << "Original array" << endl;
printArray(cout, names, CELLS);
cout << endl;
sortArray(names, CELLS);
cout << "Sorted array" << endl;
printArray(cout, names, CELLS);
cout << endl;
} // end main
// write FUNCTION 1
void printArray(ostream & out, const string data[], int cellsUsed)
{
for (int i = 0; i < cellsUsed; i++)
{
out << data[i] << " ";
}
}
// write FUNCTION 2
void sortArray(string data[], int cellsuse)
{
}
Explanation / Answer
#include <iostream>
#include <string.h>
using namespace::std;
// function will display on cout the contents of an arrary - FUNCTION 1
void printArray(ostream & out, const string data[], int cellsUsed);
// function will sort an array - FUNCTION 2
void sortArray(string data[], int cellsUsed);
// NOTE: in the string class the assignment operator and all of the relational operators
// have been overloaded
// Thus, in your sort algorithm you can use data[i] < data[j]
int main()
{
const int CELLS = 5;
string names[CELLS] = { "tom", "mary", "ann", "bill", "carol" };
cout << "Original array" << endl;
printArray(cout, names, CELLS);
cout << endl;
sortArray(names, CELLS);
cout << "Sorted array" << endl;
printArray(cout, names, CELLS);
cout << endl;
return 0;
} // end main
// write FUNCTION 1
void printArray(ostream & out, const string data[], int cellsUsed)
{
for (int i = 0; i < cellsUsed; i++)
{
out << data[i] << " ";
}
}
// write FUNCTION 2
void sortArray(string data[], int cellsuse)
{
for(int i=0; i<cellsuse; i++)
{
for(int j=i+1; j<cellsuse; j++)
{
if(strcmp(data[i].c_str(), data[j].c_str()) > 0)
{
string temp = data[i];
data[i] = data[j];
data[j]=temp;
}
}
}
}
------------------------------------------------------------------------------------------------
OUTPUT
Original array
tom mary ann bill carol
Sorted array
ann bill carol mary tom
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.