【问题标题】:Add bubble sort code to arrange the list添加冒泡排序代码来排列列表
【发布时间】:2017-07-02 04:57:45
【问题描述】:

这是我目前的程序:

    #include <iostream>
    #include <string>

    using namespace std;

    template <class type>
    void display( type list[], int size );

    template <class type>
    void bubblesort( type list[], int size);

在我的主要功能中,我有列表。

    int main()
    {
        const int SIZE = 5;
        string nameList[SIZE] = {"Bob", "Allen", "Beth", "Zebra", 
    "Hamburger" };
        int numberList[SIZE] = {88, 23, 74, 45, 78};


        //display list 1
        display(nameList, SIZE);

        //display list 2
        display(numberList, SIZE);

        system("pause");
        return 0;
    }

这就是我显示列表的方式:

    template <class type> //template must be included above 
    void display( type list[], int size )
    {
        for( int x = 0; x < size; x++ )
        {
            cout << list[x] << endl;
        }
    }

这是我想包含冒泡排序的地方,但我不知道如何。

    template <class type>
    void bubblesort( type list[], int size)
    {

    }

【问题讨论】:

  • 请清楚您尝试过的内容以及您在哪里遇到错误
  • @RomanAnanyev 你这是什么意思?
  • @OSVALDOTORRES -- 其他一切似乎都很好 -- 你唯一做的就是输入和输出 -- 老实说,这不是一个伟大的成就.真正的测试,就是想出逻辑来计算冒泡排序,你什么都没写。
  • 维基百科在bubblesort上有一个不错的页面,包括几个如何实现它的伪代码示例。

标签: c++ sorting


【解决方案1】:

试试这个代码。

void bubblesort(type list[], int size)

{ for(int i=0;i

     {
        int flag=0;

        for(int j=0;n<size-i-1;j++)

             {
                    if(list[j]>list[j+1])

                        {
                             int temp=list[j];
                             list[j]=list[j+1];
                             list[j+1]=temp;
                             flag=1;
                        }
               }
        if(flag==1) break;
       }

}

【讨论】:

    【解决方案2】:

    为整数实现冒泡排序很简单。一个简单的冒泡排序谷歌将为您解答。字符串略有不同。你必须抓住字符串的第一个字符

    {
    string myString = "cat";
    
    char c = myString[0];
    
    //stringName[0] obtains the first character, since string are basically character array objects, so they can be accessed like a normal array
    
     }
    
    You can then cast that character to an integer
    
    {
    
    char firstChar = myString[0];
    
    int firstCharValue = (int)firstChar
    
    //or just as 
    
    int firstCharValue = (int)myString[0]
    
    }
    

    然后你回到一个简单的整数冒泡排序。

    【讨论】:

      猜你喜欢
      • 2016-05-17
      • 2014-03-13
      • 1970-01-01
      • 2013-04-30
      • 1970-01-01
      • 1970-01-01
      • 2018-09-10
      • 2018-04-25
      • 2023-03-07
      相关资源
      最近更新 更多