随机数排序问题(补)

lchh0917 lchh0917 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
高手帮忙!!!我这个程序通过产生随机数,然后进行相关排序,问题是我选择了'直接插入法排序'后,再选择其他排序时调用的是上一次排序完成后的数组,即不是原始无序随机数,也就是这里用的是地址传递,怎么修改为值传递,才保证每次进行排序时调用的数组是原始随机数。。。

#include<iostream.h>
#include <algorithm>
#include<stdlib.h>
#include <time.h>
#include <tchar.h>

#define ARRAY_SIZE 20
using namespace std;

void print()
{
cout<<"====== 要使用直接插入法排序请按i ======"<<endl;
cout<<"====== 要使用直接选择法排序请按s ======"<<endl;
cout<<"====== 要使用起泡法排序请按b ======"<<endl;
cout<<"====== 要重新生成随机数请按r ======"<<endl;
cout<<"********上述排序指令均可重复执行*********"<<endl;
cout<<"====== 退出本程序请按x ======"<<endl;
}

void InsertSort(int arrForSort[],int nLength) //直接插入排序
{
int i,j,temp,n;
for(i=1;i<nLength;i++)
{
temp=arrForSort[i];
for(j=i;j>0&&temp<arrForSort[j-1];j--)
arrForSort[j]=arrForSort[j-1];
arrForSort[j]=temp;
for(n=0;n<nLength;n++)
cout<<arrForSort[n]<<" ";
cout<<endl;
}
}


void SelectSort(int arrForSort[],int nLength) //直接选择排序
{
int min,temp,
i,j,n;
for(i=0;i<nLength-1;i++)
{
min=i;
for(j=i+1;j<nLength;j++)
if(arrForSort[j]<arrForSort[min]) min=i;
temp=arrForSort[i];
arrForSort[i]=arrForSort[min];
arrForSort[min]=temp;
for(n=0;n<nLength;n++)
cout<<arrForSort[n]<<" ";
cout<<endl;
}
}

void BubbleSort(int arrForSort[],int nLength) //起泡法排序
{
int i,j,temp,n;
i=nLength-1;
while(i>0)
{
for(j=0;j<i;j++)
{
if(arrForSort[j+1]<arrForSort[j])
{temp=arrForSort[j+1];
arrForSort[j+1]=arrForSort[j];
arrForSort[j]=temp;}
}
i--;
for(n=0;n<nLength;n++)
cout<<arrForSort[n]<<" ";
cout<<endl;
}
}

void put_array(int x[],int size) {
for(int i=0;i<size;i++)
cout<<x[i]<<" ";
cout<<endl;
}

int getrand(int min,int max) {
int m;
m=(max-min);
m=min+double(rand())/RAND_MAX*m ;
return m;
}

void Exit()
{
exit(0);
}

void main ()
{
int i;
int x[ARRAY_SIZE];
char ch;
srand( (unsigned)time( NULL ) );
for (i=0;i<ARRAY_SIZE;i++)
{
x[i]=getrand(1,100);
}
cout<<"====== 1~100内随机生成的20个数: ======"<<endl;
cout<<"x[20]:";
put_array(x,ARRAY_SIZE);
cout<<endl;
print();
cout<<endl;
while(cin>>ch)
{
switch (ch)
{
case 'i':
cout<<"====== 下面将进行直接插入排序过程演示: ======"<<endl;
InsertSort(x,ARRAY_SIZE);
cout<<"x[20]:";
put_array(x,ARRAY_SIZE);
cout<<endl;
break;
case 's':
cout<<"====== 下面将进行直接选择法排序过程演示: ====== "<<endl;
SelectSort(x,ARRAY_SIZE);
cout<<"x[20]:";
put_array(x,ARRAY_SIZE);
cout<<endl;
break;
case 'b':
cout<<"====== 下面将进行起泡法排序过程演示: ====== "<<endl;
BubbleSort(x,ARRAY_SIZE);
cout<<"x[20]:";
put_array(x,ARRAY_SIZE);
cout<<endl;
break;
case 'r':
cout<<"====== 重新生成随机数: ======"<<endl;
srand( (unsigned)time( NULL ) );
for (i=0;i<ARRAY_SIZE;i++)
{
x[i]=getrand(1,100);
}
cout<<"x[20]:";
put_array(x,ARRAY_SIZE);
cout<<endl;
break;
case 'x':
Exit();
break;
default:cout<<"====== 请按上述提示输入正确指令: ====== "<<endl;
}
}
}
...全文
评论 8
收藏 已收藏
分享
返回顶部
lchh0917
C++ 语言 65,212 成员 250,513 内容