为什么我的数组无法正确打印(气泡排序)

时间:2020-04-26 21:34:40

标签: c++ bubble-sort

该程序应该根据购买量最多,碗数最少的碗,打印出最受欢迎的拉面口味。

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

(已售出1个,用于阵列中的第一种口味)

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

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

(阵列中第4种口味的4种已售出)

输出

鸡肉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;
}
}

2 个答案:

答案 0 :(得分:1)

我认为您应该迭代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]);    
         } 
     }
 }

答案 1 :(得分:0)

您可以像这样在您的方案中实现冒泡排序

  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++;
  }