64,642
社区成员
发帖
与我相关
我的任务
分享
#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;
}
}
}