#include<stdio.h>
#include<string>
#include<iostream>
#include<time.h>
using namespace std;
int randomInRange(int start, int end) //产生在start和end之间的随机数;
{
srand(time(NULL));
return start + rand()%(end-start+1);
}
void insertsort(int *a) //插入排序
{
int temp;
for(int i=1;i<10;i++)
for(int j=0;j<i;j++)
{
if(*(a+i)<*(a+j))
{
temp=*(a+i);
*(a+i)=*(a+j);
*(a+j)=temp;
}
}
for(int i=0;i<10;i++)
cout<<*(a+i)<<" ";
cout<<endl;
}
int partition(int a[],int start,int end) //将数组划分为前后两个子序列,前面的子序列小于关键字,后面的子序列大于关键字;
{
int index= randomInRange(start,end);
swap(a[index],a[end]);
int small=start-1;
for(index=start;index<end;index++)
{
if(a[index]<a[end])
{ ++small;
if(small!=index)
swap(a[small],a[index]);
}
}
++small;
swap(a[small],a[end]);
return small;
}
void quicksort(int a[],int low,int high) //快速排序
{
int index=partition(a,low,high);
if(index>low)
quicksort(a,low,index-1);
if(index<high)
quicksort(a,index+1,high);
}
void selectionsort(int a[],int low,int high) //选择排序
{
for(int j=high-1;j>=0;j--)
{
int max=a[low];
int index=low;
for(int i=low;i<=j;i++)
{
if(a[i]>max)
{
max=a[i];
index=i;
}
}
a[index]=a[j];
a[j]=max;
}
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
cout<<endl;
}
void bubble_sort(int a[],int len)
{
for(int i=0;i<len-1;i++)//执行len-1遍循环
for(int j=0;j>len-1-i;j++)//每次循环遍历前面len-i个数,因为后面的i个数是排序好的最大的数;
{
if(a[j]>a[j+1])//比较前后两个数,如果前面的大于后面的,就交换
{
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
int main(){
int a[10]={2,1,3,6,8,5,9,10,4,7};
insertsort(a);
quicksort(a,0,9);
selectionsort(a,0,9);
bubble_sort(a,10);
return 0;
}