### bobble sort algorithm, need help

you are asked to read 10 names (String type) from an input file let's call it in.text, save it to an array
(called name [10]), sort them (alphabetically). Print the result to an output file calls it out.txt you need
to use bobble sort algorithm.

Here is my problem, my output shows only 9 names on the list, and sometimes one of the names shows more than once.

Thanks for help!

 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 #include #include #include #include #include using namespace std; int main() { vector names; ifstream inFileNames; ofstream outFileNames; //Open names file inFileNames.open("d:\\in.txt"); //read names string readName; for(; getline(inFileNames, readName);) { names.push_back(readName); } //close name file inFileNames.close(); //create names file outFileNames.open("d:\\out.txt"); //output to the namegrades file for(int k=1; k<=9; k++) { for(int n=0; n<=8; n++) { if (names[n] > names[n+1]) names[n].swap(names[n+1]); } outFileNames< names[n+1]) names[n].swap(names[n+1]); } cout<
First fundamental issue:
How many elements does the "names" contain at line 26? You don't check.
Nevertheless, you do assume some number in the following loops.

You do appear to sort the list twice for no reason. Sort first, then output to the two destinations (outfile and cout).

To your question: You do print elements [1-9]. That is 9 values.

I have long forgotten the algorithm for bubble, so I just have an eerie feeling about your implementation.
Here is my take on your problem.

 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 #include #include #include using namespace std; #define NUMNAMES 20 void bubbleSort(string list[], int length); int main(int argc, const char * argv[]) { string names[NUMNAMES]; ifstream inFile; inFile.open("inData.txt", ifstream::in); if (!inFile) { cerr << "Error: in file could not be opened" << endl; return -1; } int count = 0; while (getline(inFile, names[count++], '\n')) { } inFile.close(); bubbleSort(names, NUMNAMES); return 0; } // BubbleSort algorithm source: //C++ PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM DESIGN // By D.S. MALIK 5th Edition void bubbleSort(string list[], int length){ string temp; int iteration; int index; for (iteration = 0; iteration < length; iteration++) { for (index = 0; index < length - iteration; index++) { if (list[index] > list[index + 1]) { temp = list[index]; list[index] = list[index + 1]; list[index + 1] = temp; } } } // printing list. for (int i = 0; i < length; i ++) { cout << list[i] << endl; } }
Last edited on
Topic archived. No new replies allowed.