[英]why won't my array print correctly (bubble sort)
這個程序應該根據購買的碗的最高數量到最低打印出最受歡迎的拉面口味。
但是,如果我隨機輸入出售的碗數如下
(1 個已售出 - 用於陣列中的第一種口味)
( 2 個已售出 - 用於陣列中的第二種口味)
(3 個已售出 - 用於陣列中的第三種口味)
(陣列中的 4 個以第四種口味出售)
output
雞 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;
}
}
我認為您應該遍歷 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]);
}
}
}
您可以像這樣在您的場景中實現冒泡排序
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++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.