泡泡排序的书名

时间:2017-02-21 10:55:44

标签: c++ bubble-sort

我需要制作书籍分类的C ++代码:

  1. 显示书名。
  2. 按字母顺序显示书名。
  3. 我能够做到第一次,但我在显示书籍的字母顺序方面遇到了困难。

    这是我的代码:

    #include"stdafx.h"
    #include <iostream>
    #include <string>
    #include <conio.h>
    #include <algorithm>
    #include <cstring>
    #include <map>
    #include <stdlib.h>
    #include <time.h>
    
    using namespace std;
    
    const int MAX = 5;
    
    void BubbleSort(string books, int max);
    
    int main(int argc, const char * argv[])
    {
        string books[MAX];
    
        //inputs
        std::cout << "Enter Book titles: \n";
        for (int i = 0; i < MAX; i++)
        {
            std::cout << "Book [" << i << "]: ";
            //cin >> books[i];
            getline(std::cin, books[i]);
    
        }
        // print the titles stored in books[i] variable
        cout << "Book Titles Entered \n\n";
        for (int i = 0; i < MAX; i++)
        {
            std::cout << "Book No." << i << ": ";
            cout << books[i] << endl;
    
        }
    
        // print the titles after sort
        cout << "Book Titles In Sort Ascending \n\n";
        for (int i = 0; i < MAX; ++i)
            cout << books[i] << "\n";
    
    }
    
    void BubbleSort(string books, int size)
    {
        int result;
        for (int pass = 0; pass < size - 1; ++pass)
        {
            for (int i = 0; i < MAX - 1 - pass; ++i)
            {
                result = string (books[i], books[i + 1]);
                if (result > 0) {
                    swap(books[i], books[i + 1]);
                }
            }
        }
    
        system("pause");
    }
    

1 个答案:

答案 0 :(得分:1)

您没有致电BubbleSort

另一方面,除了这是家庭作业或类似作品,你必须实施冒泡排序,我建议你使用std::sort。此外,使用动态数组替换静态数组,例如std::vector

std::vector<std::string> books;
// <input here>: use books.push_back to insert new strings
std::sort(books.begin(), books.end());

如果您事先知道书籍数量,则可以预先分配内存,从而降低插入的复杂性:books.reserve(MAX)