【问题标题】:why won't my array print correctly (bubble sort)为什么我的数组不能正确打印(冒泡排序)
【发布时间】:2020-04-26 21:34:40
【问题描述】:

这个程序应该根据购买的碗的最高数量到最低打印出最受欢迎的拉面口味。

但是,如果我随机输入以下出售的碗数

(已售出 1 个 - 用于阵列中的第一个风味)

(已售出 2 个 - 阵列中的第二种口味)

(3 个已售出 - 阵列中的第三种口味)

(阵列中的第四种口味)

输出

鸡 4

__ 3

__ 2

__ 1

但如果我按降序分配销售量,则程序有效

非常感谢您的反馈

#include <iostream>
#include <string>
using namespace std;


int main ()
{
    string flavor[]={"fish","lamp","steak" ,"chicken"}   ;
    int scoops[100]={};
    int sum=0;
    int x=0;

    for(x=0;x<4;x++)
    {
        cout <<"enter amount of bowls for the following ramen flavor :"<<flavor[x] <<endl;
        cin>>scoops[x];
        sum=scoops[x]+sum;
    }

    cout <<"total number of bowls is "<<sum<<endl;
    cout <<"list of the most popular flavors to least popular flavors "<<endl;//bubble sort


    int i=0,j=0,temp,char tempf;

    if(scoops[j]<scoops[j+1])
    {
        temp=scoops[j];
        scoops[j]=scoops[j+1];
        flavor[j]=flavor[j+1];
        scoops[j+1]=temp;
        flavor[j+1]=tempf;
    }



for (int a=0;a<4;a++)
{
    cout <<flavor[a] <<"\t"<<scoops[a]<<endl;
}
}

【问题讨论】:

  • 冒泡排序需要一个循环。您的代码中没有循环,只有一个 if 语句。
  • 使用std::swap(scoops[j], scoops[j+1]); std::swap(flavor[j], flavor[j+1]); 进行交换。您当前的交换是错误的,因为您在分配 flavor[j] 之前没有保存风味。
  • 您的程序没有按原样编译(例如,您试图将char tempf 分配给std::string 变量)。请提供minimal reproducible example

标签: c++ bubble-sort


【解决方案1】:

你可以像这样在你的场景中实现冒泡排序

  int i = 0;
  bool is_sorted = true;
  int number_of_scoop_records = 4;

  // We keep looping over the array until all the elements are sorted
  while(true) {

    if(i >= (number_of_scoop_records-1)) {
      // All elements sorted, nothing to do anymore
      if(is_sorted)
        break;

      // Lets go around again
      i = 0;
      is_sorted = true;
      continue;
    }

    // Unsorted elements found
    if(scoops[i+1] < scoops[i]) {
      is_sorted = false;
      std::swap(scoops[i+1], scoops[i]);
    }
    i++;
  }

【讨论】:

    【解决方案2】:

    我认为你应该遍历 scoops[] 数组,检查它的值并使用 STL::algorithm 提供给我们的 swap() 函数。

    int length = sizeof(flavor)/sizeof(flavor[0]);
    for (int i = 0; i < length-1; ++i)
    {
         for (int j = i+1; j < length; ++j)
         {    
             if (scoops[i] > scoops[j])
             {
                 swap(flavor[i], flavor[j]);    
             } 
         }
     }
    

    【讨论】:

    • 即使数组已经排序,你的实现也会继续循环。
    • 哦,对了,一切都取决于用户的输入。您的代码看起来很酷,但在不确定的勺子长度中,线性 burble 排序算法实现可能更微妙。
    • 如果您处理的是非常短的数组,您的方法并不是真正的问题,但是包含数千个元素的数组将始终等于百万次迭代。我会投票赞成你的代码的简洁性。
    猜你喜欢
    • 1970-01-01
    • 2020-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-29
    • 2015-09-12
    • 2017-06-28
    • 1970-01-01
    相关资源
    最近更新 更多