按顺序排序数字-冒泡排序- c++
sorting numbers in order - bubble sort - C++
我需要做一个程序来生成随机数并对它们进行排序。程序需要从srand()函数生成它们来初始化随机数序列。程序应按升序或降序显示列表,所有三个必须并排显示。
我的代码中有一个问题,按升序和递减顺序排序数字。
这是我的代码:
using namespace std;
int main()
{
int n,j=0;
int temp;
int compt=2;
int compt2=2;
int tab [50];
int random = 0;
cout<< "n Bonjour!";
do
{
cout<< "nn Entrer la longeur de liste que vous desirez (5 a 50) : ";
cin>> n;
if(5>n || n>50)
{
cout<< "n ``ERREUR``";
}
}while (5>n || n>50);
srand((unsigned)time(NULL));
cout<<"n ";
for(j=0;j<n;j++)
{
random = (rand()%n+1);
tab [j] = random;
cout<<tab[j]<<" ";
}
while(compt>1)
{
compt=0;
for (j=0;j<n;j++)
{
if(tab[j]>tab[j+1])
{
temp = tab[j];
tab[j] = tab [j+1];
tab [j+1] = temp;
compt+=1;
}
}
}
cout<<"n apres tri croissant"<<endl;
for(j=0;j<n;j++)
{
cout<<tab[j-1]<<" ";
}
cout<<"n apres tri deroissant"<<endl;
for(j=(n-1);j>=0;j--)
{
cout<<tab[j-1]<<" ";
}
cout<<"test";
}
thanks in advance
看看如何使用std::算法来处理排序。
在此代码中:
for (j=0;j<n;j++)
{
if(tab[j]>tab[j+1])
有一个错误。数字n
是数组的大小,到最大数组索引是n-1
。在此代码中,在最后的比较中,您将tab[n-1]
与tab[n]
进行比较。
试着把它改成:
for (j=0;j<(n-1);j++)
{
if(tab[j]>tab[j+1])
试试这样做:
while(compt>1){
compt=0;
int aux = tab[0]; //We create an auxiliar variable with 1st value in array
for (j=1;j<n;j++){
if(aux>tab[j]){ //We sort it
temp = aux;
aux = tab [j];
tab [j] = temp;
compt++; //As you're adding +1 each time, you can change compt += 1 for compt++ (does the same)
}
}
}
此代码为
for(j=0;j<n;j++){
cout<<tab[j-1]<<" ";
}
如果我没有错的话,因为我现在无法测试它,它应该是:因为它会在第一个位置打印tab[0-1],即(tab[-1]),我们都知道,它不存在。
for(j=0;j<n;j++){
cout<<tab[j]<<" ";
}
应该可以
相关文章:
- 如何在C++中对数组进行冒泡排序
- 我想在 c++ 中对单向链表进行冒泡排序,但我一直面临左值错误,无法解决它
- 在C++中使用冒泡排序时出现意外值
- 冒泡排序中所需的交换次数,而无需实际对其进行排序
- 如何对文件中数组中的单个列进行冒泡排序?C++
- 需要关于如何将我的随机数数组连接到冒泡排序的帮助
- 冒泡排序无法对C++中的对象的动态数组进行排序
- 冒泡排序.C++
- 链表的冒泡排序
- 有没有选择排序优于冒泡排序的输入
- C++:如何使用冒泡排序来重新排列我的数据
- 冒泡排序随机数
- 矢量下标超出范围-冒泡排序
- 使用冒泡排序比较类对象
- 在c++中使用冒泡排序/交换对字符串进行排序
- 矢量下标超出范围错误,C++,冒泡排序
- 冒泡排序、选择排序和插入排序
- 使用冒泡排序c++对结构数组的成员进行优先级排序
- 冒泡排序链表C++
- 行搜索和冒泡排序的问题