/*主要思想:
* 1、插入排序:若只有一个元素时看做有序,将第二个、第三个……第n个元素依次插入有序(升序或降序)的序列中,将第n个元素插入后,整个序列为有序。
* 2、冒泡排序:从第一个元素开始,依次将其和其后的一个元素做比较,若该元素大于(或小于)其后的元素,将两个元素交换顺序,一趟结束后,第n个元素为最大(或最小* ),进行n-1趟后,整个序列有序。
* 3、选择排序:遍历n-1趟,每趟选出最大(或最小)的元素,将其放在队首(或队尾),n-1趟后,整个序列有序
*/
#include <stdio.h>
#include <iostream>
#include <time.h>
#include <windows.h>
using namespace std;
#define N 10
void InsertSort(int a[], int size)
{
int i,j;
int temp;
for(i=0; i<size-1; i++)
{
temp=a[i+1];
j=i;
while(j>-1&&temp<a[j])
{
a[j+1]=a[j];
j--;
}
a[j+1]=temp;
}
return;
}
void BubbleSort(int a[], int size)
{
int i=size,j;
int temp;
while(i>0)
{
for(j=0; j<i-1; j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
i--;
}
return ;
}
void SelectSort(int a[], int size)
{
int i,j,k;
int temp;
for(i=0; i<size-1; i++)
{
k=i;
for(j=i+1; j<size; j++)
{
if(a[j]<a[k])
k=j;
}
if(k!=i)
{
temp=a[k];
a[k]=a[i];
a[i]=temp;
}
}
return ;
}
int main()
{
int a[N];
int choice=0;
while(1)
{
for(int i=0; i<N; i++)
{
srand(i);
srand(i+rand()%100+time(0));
a[i]=rand()%500;
printf("%d ", a[i]);
//Sleep(80);
}
cout<<endl;
cout<<"1、插入排序"<<endl;
cout<<"2、冒泡排序"<<endl;
cout<<"3、选择排序"<<endl;
cout<<"0、退出"<<endl;
cout<<"请选择:";
scanf("%d",&choice);
switch(choice)
{
case 1:
InsertSort(a, N);
for(i=0; i<N; i++)
cout<<a[i]<<" ";
cout<<endl;
system("pause");
break;
case 2:
BubbleSort(a, N);
for(i=0; i<N; i++)
cout<<a[i]<<" ";
cout<<endl;
system("pause");
break;
case 3:
SelectSort(a, N);
for(i=0; i<N; i++)
cout<<a[i]<<" ";
cout<<endl;
system("pause");
break;
case 0:
return 0;
default:
printf("输入的数据不正确,请重新输入……\n");
}
system("cls");
}
system("pause");
return 0;
}