(1)随机生成一组关键码(关键码为整型,取值范围为0~99);
(2)采用插入排序算法进行排序,输出排序结果;
(3)采用交换排序算法进行排序,输出排序结果;
(4)采用选择排序算法进行排序,输出排序结果;
#include <iostream>
#include <string>
#include <ctime>
#include <stdlib.h>
using namespace std;
//插入排序
void insertSort(int r[],int n)
{
int i,j;
for (i=2;i<=n;i++){
r[0]=r[i];
for( j=i-1;r[0]<r[j];j--)
r[j+1]=r[j];
r[j+1]=r[0];
}
}
//交换排序
void BubbleSort(int r[],int n)
{
int i,j;
for (i = 0; i < n-1; i++){
for (j= 0; j < n-1-i; j++){
if (r[j] > r[j+1]){
int temp = r[j+1];
r[j+1] = r[j];
r[j] = temp;
}
}
}
}
//选择排序
void SelectSort(int r[],int n){
int i,j;
for (i=1; i < n; i++){
int index = i;
for (j=i+1; j<=n;j++){
if (r[j] < r[index]){
index = j;
}
} //找到了最小的值再交换
if(index!=i){
int temp = r[i];
r[i] = r[index];
r[index] = temp;
}
}
}
void useRand(int r[],int size)
{
srand((unsigned)time(NULL));
cout << "the rand number is:" <<endl;
for(int i=0;i<=9;i++)
{
r[i]=rand()%99+1;
cout << r[i] << ",";
}
cout << endl;
}
void copy(int a[],int b[],int n)
{
for(int i=0;i<n;i++)
b[i]=a[i];
}
void print(int a[10],int n)
{
for(int i=0;i<n;i++)
cout << a[i] << ",";
cout << endl;
}
int main(){
int r[10],a[10],b[10],c[10];
useRand(r,10);
copy(r,a,10);
copy(r,b,10);
copy(r,c,10);
insertSort(a,10);
cout << "插入排序后:" << endl;
print(a,10);
BubbleSort(b,10);
cout << "交换排序后:" << endl;
print(b,10);
SelectSort(c,10);
cout << "选择排序后:" << endl;
print(c,10);
return 0;
}