[英]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<< "\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處理排序。
在此代碼中:
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]<<" ";
}
那應該工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.