[英]C++ Struct Bubble Sorting
我必須僅使用 iostream 和 fstream 對 C++ 結構進行冒泡排序,但似乎有些問題(請參閱下面的輸入和輸出)。
void sortCarsByPrice(Cars carsArray[])
{
int index1;
int index2;
int index3;
int swap;
int yearTemp;
char makeTemp;
char modelTemp;
float priceTemp;
int availTemp;
do
{
swap = 0;
for (index1 = 0; index1 < 5; index1++)
{
if (carsArray[index1].price > carsArray[index1 + 1].price)
{
yearTemp = carsArray[index1].year;
carsArray[index1].year = carsArray[index1 + 1].year;
carsArray[index1 + 1].year = yearTemp;
for (index2 = 0; carsArray[index1].make[index2] != '\0' && carsArray[index1 + 1].make[index2] != '\0'; index2++)
{
makeTemp = carsArray[index1].make[index2];
carsArray[index1].make[index2] = carsArray[index1 + 1].make[index2];
carsArray[index1 + 1].make[index2] = makeTemp;
}
for (index3 = 0; carsArray[index1].model[index3] != '\0' && carsArray[index1 + 1].model[index3] != '\0'; index3++)
{
modelTemp = carsArray[index1].model[index3];
carsArray[index1].model[index3] = carsArray[index1 + 1].model[index3];
carsArray[index1 + 1].model[index3] = modelTemp;
}
priceTemp = carsArray[index1].price;
carsArray[index1].price = carsArray[index1 + 1].price;
carsArray[index1 + 1].price = priceTemp;
availTemp = carsArray[index1].available;
carsArray[index1].available = carsArray[index1 + 1].available;
carsArray[index1 + 1].available = availTemp;
swap += 1;
}
}
}
while (swap != 0);
cout << "SORTED!" << endl;
return;
}
輸入:
0 2014 Toyota Tacoma $115.12 0
1 2015 Ford Fusion $90.89 1
2 2009 Dodge Neon $45.25 0
3 2015 Ford F150 $112.83 1
4 2016 Subaru Outback $71.27 1
輸出:(排序后)
0 999984304 �yota Ծ0#on $-1.84172e+33 32566
1 2009 Dodg Neonma $45.25 0
2 2016 Subae Outb $71.27 1
3 2015 Ford Fusi $90.89 1
4 2015 Fordru F150U�� $112.83 1
如果數組中有 5 個元素,並且您使用index1 + 1
作為循環內的索引,那么您只希望index1
上升到 4。正如所寫,您允許index1
上升到 5,這意味着index1 + 1
是 6,這大概是數組的末尾。
更好的是,您可能希望向函數添加一個額外的參數,即數組中元素的數量,而不是在排序函數中間添加一個神秘(且不正確)的 5。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.