c++ - 按顺序对数字进行排序 - 冒泡排序 - C++

标签 c++ sorting numbers

我需要编写一个程序来生成随机数并对它们进行排序。 程序需要从 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<< "\n\n 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";



}

提前致谢

最佳答案

查看使用 std::algorithms 处理排序。

关于c++ - 按顺序对数字进行排序 - 冒泡排序 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22701341/

相关文章:

java - 从头开始对列表进行排序

sql-server - 当文本包含非日语字符时,日语中的 SQL 排序顺序会中断

javascript - 10次​​退出后窗口关闭事件的反馈调查模式,无论相同或不同用户

c++ - 从 stdin 读取时 zmq_poll 不监听信号

c++ - OOP 设计 - protected 成员不在自己的类中使用 - 但仅在子类中使用

c++ - 如何正确删除动态数组指针

Java极小数算术运算

c++ - 在 C++ 中编写自定义异常类时如何重载 throw 函数?

javascript - 什么更快 - 将 2 个排序数组合并为一个没有重复值的排序数组

c# - 将由特定于文化的数字组成的 Unicode 字符串转换为整数值