![]() |
#2
寒风中的细雨2011-05-17 23:56
|

#include<iostream>
#include<iomanip>
using namespace std;
void B(int r[],int );
#include<ctime>
#include<cstdlib>
int main()
{
const int M=100000;
int size;
int A[M];
srand(time(0));
for(int y=1;y<M;y++)
{
A[y]=1+rand()%100000;
}
cout<<"请输入要排序的范围数:";
cin>>size;
cout<<endl;
time_t first,end;
first=clock();
B(A,size);
end=clock();
cout<<"所需的时间为: "<<double(end-first);
return 0;
}
void B(int r[], int n)
{
int temp;
int exchange;
int bound;
exchange=n-1; //第一趟起泡排序的范围是r[0]到r[n-1]
while (exchange) //仅当上一趟排序有记录交换才进行本趟排序
{
bound=exchange;
exchange=0;
for (int j=0; j<bound; j++) //一趟起泡排序
if (r[j]>r[j+1])
{
temp=r[j];
r[j]=r[j+1];
r[j+1]=temp;
exchange=j; //记录每一次发生记录交换的位置
}
}
for(int i=0;i<n;i++)
cout<<r[i]<<setw(6);
}
假如你对随机产生的随机数进行排序,第一个数都是-858993460 其余的排序没错。为什么出现这种情况,请大家帮忙看看代码解释一下,谢谢了 #include<iomanip>
using namespace std;
void B(int r[],int );
#include<ctime>
#include<cstdlib>
int main()
{
const int M=100000;
int size;
int A[M];
srand(time(0));
for(int y=1;y<M;y++)
{
A[y]=1+rand()%100000;
}
cout<<"请输入要排序的范围数:";
cin>>size;
cout<<endl;
time_t first,end;
first=clock();
B(A,size);
end=clock();
cout<<"所需的时间为: "<<double(end-first);
return 0;
}
void B(int r[], int n)
{
int temp;
int exchange;
int bound;
exchange=n-1; //第一趟起泡排序的范围是r[0]到r[n-1]
while (exchange) //仅当上一趟排序有记录交换才进行本趟排序
{
bound=exchange;
exchange=0;
for (int j=0; j<bound; j++) //一趟起泡排序
if (r[j]>r[j+1])
{
temp=r[j];
r[j]=r[j+1];
r[j+1]=temp;
exchange=j; //记录每一次发生记录交换的位置
}
}
for(int i=0;i<n;i++)
cout<<r[i]<<setw(6);
}