2017-02-21 200 views
0

我需要的書名排序的C++代碼:冒泡排序

  1. 顯示書名。
  2. 按字母順序顯示書名。

我能夠做第一次,但我在顯示書籍的字母順序時遇到困難。

這裏是我的代碼:

#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

字符串比較應該是:'result = string(books [i],books [i + 1]);'? – xander

回答

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)

+2

或者使用'''std :: array''' – Paul92