在工作期间,将内容过程重要的内容做个备份,下面内容内容是关于C++控制一组字符串按照字母顺序排序的内容,希望对小伙伴们有些用处。
discussed in Section 5.12.2 and the techniques for sorting
arrays developed in Chapter 4 to write a program that
alphabetizes a list of strings. Use the names of 10 or 15
towns in your area as data for your program.
Listing of the cities in alphabetical order
Print out the listing of cities stored
function BubbleSort
Do number of runs as contained in array
Check each string with string compare
If Result value > 0 then perform a swap
until all strings are sorted in alphabetical
listing.
Return results of BubbleSort
Print out the listing of cities in alphabetical
order.
End program.
#include <conio.h>
#include <cstring>
using namespace std;
void instruct (void);
void pause ();
int main ()
{
int i = 0;
const int arraySize = 15;
"Kalihi", "Waipahu", "Pearl Harbor", "Hawaii Kai",
"Mililani", "Waikiki", "Kaneohe", "Kapolei",
"Salt Lake", "Ewa Beach", "Manoa" };
instruct ();
cout << "The original listing of cities:nn";
for ( i = 0; i < arraySize; ++i )
cout << cities[ i ] << "n" ;
pause();
BubbleSort( cities , arraySize );
cout << "The alphabetical listing of cities:nn";
for ( i = 0; i < arraySize; ++i )
cout << cities[ i ] << "n" ;
pause ();
return 0;
}
{
int result;
for ( int pass = 0; pass < size - 1 ; ++pass ){
for ( int j = 0; j < size - 1 - pass; ++j ){
result = strcmp (array[j], array[j+1]);
if (result > 0)
swap ( array[j] , array[j+1] );
}
}
}
void instruct (void)
{
cout << "This program will take a lising of 15 cities located in a string "
<< "array and willnprint out the original listing of cities. It "
<< "will then take the same stringnarray, do a sting compare, sort "
<< "if necessary and rearrange the string array tonplace it in "
<< "alphabetical order. Finally it will print out the alphabetical.n"
<< "listing of the cities in the string array.n"
<< "_______________________________________________________________"
<< "_____________"
<< "n" << endl;
pause();
}
void pause ()
{
cout << "nPress any key to continue...";
getch();
cout << "r";
cout << " ";
cout << "r";
}
Program Output
This program will take a lising of 15 cities located in a string array and will
print out the original listing of cities. It will then take the same string
array, do a sting compare, sort if necessary and rearrange the string array to
place it in alphabetical order. Finally it will print out the alphabetical.
listing of the cities in the string array.
____________________________________________________________________________
The original listing of cities:
Honolulu
Aiea
Pearl City
Wahiawa
Kalihi
Waipahu
Pearl Harbor
Hawaii Kai
Mililani
Waikiki
Kaneohe
Kapolei
Salt Lake
Ewa Beach
Manoa
The alphabetical listing of cities:
Aiea
Ewa Beach
Hawaii Kai
Honolulu
Kalihi
Kaneohe
Kapolei
Manoa
Mililani
Pearl City
Pearl Harbor
Salt Lake
Wahiawa
Waikiki
Waipahu
Press any key to continue...