冒泡排序功能实现不工作 [英] bubble sort function implementation not working
问题描述
我有一个气泡排序的问题。我按照降序排列8个数字的数组;但是,当打印到屏幕时,第一个数字不在阵列中。它就像是一个出界错误,或者打印一些内存内容。任何帮助赞赏。
I'm having a problem with bubble sort. I'm sorting an array of 8 numbers in descending order; however, when printing to screen, the first number is not in the array. it is like is an out of bound error, or printing some memory content. Any help appreciated.
#include <iostream>
using namespace std;
void sortArray(int nums[]);
void printArray(int nums[]);
int main()
{
int nums[8] = {3, 6, -19, 5, 5, 0, -2, 99};
sortArray(nums);
printArray(nums);
system("pause");
return 0;
}
void sortArray(int nums[])
{
bool swap;
int temp;
do
{
swap = false;
for(int i = 0; i < 8; i++)
{
if(nums[i] < nums[i+1])
{
temp = nums[i];
nums[i] = nums[i+1];
nums[i+1] = temp;
swap = true;
}
}
}while(swap);
}
void printArray(int nums[])
{
for(int i = 0; i < 8; i++)
{
cout << nums[i] << ", ";
}
cout << endl;
}
推荐答案
我又是一个TA。
int数组,大小= 8,即索引0到7.
int array, with size = 8, i.e. index 0 to 7.
在你的for(int i = 0; i <8; i ++)中,你试图访问nums [i + 1],当i = 7时会发生什么?访问数字[8],对吗?
In your for(int i=0; i<8; i++) you're trying to access nums[i+1], what happens when i = 7? Access nums[8], right?
此外,这不是一个气泡排序,它关闭,但不是实际。再次阅读您的教科书。
Furthermore, this is NOT a bubble sort, its closed to, but not actually. Read your textbook again.
这篇关于冒泡排序功能实现不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!