#include<iostream>
using namespace std;
void Insertsort(int a[],int length)
{
/*int i,j,temp;
for(i=0;i<length-1;i++)
{
j=i+1;
if(a[j]<a[i])
{
temp=a[j];
while(i>=0&&temp<a[i])
{
a[i+1]=a[i];
i--;
}
a[i+1]=temp;
i=j-1;
}
}*/
int i,j,temp,d=length/2;
while(d>0)
{
for(i=0;i<length;i++)
{
j=i-d;
//temp=a[i];
while(j>=0&&a[j+d]<a[j])
{
temp=a[j+d];
a[j+d]=a[j];
a[j]=temp;
j=j-d;
}
//a[j+d]=temp;
}
d/=2;
}
}
void bulle(int a[],int length)
{
for(int i=0;i<length;i++)
for(int j=length-1;j>i;j--)
{
if(a[j]<a[j-1])
{
int temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
}
}
}
void quicksort(int a[],int left,int right)
{
if(left>=right)
return;
int temp=a[left];
int i=left,j=right;
while(i<j)
{
while(j>i&&a[j]>=temp)
{
j--;
}
swap(a[i],a[j]);
while(j>i&&a[i]<=temp)
{
i++;
}
swap(a[i],a[j]);
}
cout<<endl;
quicksort(a,left,i-1);
quicksort(a,i+1,right);
}
void merge(int a[],int first,int mid,int last)
{
if(first>mid||mid>last)
return;
int i=first,j=mid+1,k=0;
int tempa,tempb;
int *temp=(int*)malloc(sizeof(int)*(last-first+1));
while(i<=mid||j<=last)
{
if(i>mid)
tempa=INT_MAX;
else
tempa=a[i];
if(j>last)
tempb=INT_MAX;
else
tempb=a[j];
temp[k++]=(tempa<tempb?(i++,tempa):(j++,tempb));
}
for(int t=first,k=0;t<=last;t++)
{
a[t]=temp[k++];
}
}
void mergesort(int a[],int start,int end)
{
if(start>=end)
return;
int mid=(end+start)/2;
mergesort(a,start,mid);
mergesort(a,mid+1,end);
merge(a,start,mid,end);
}
void select(int a[],int length)
{
for(int i=0;i<length;i++)
{
int min=a[i],mark;
for(int j=i+1;j<length;j++)
{
if(min>a[j])
{
min=a[j];
mark=j;
}
}
if(min<a[i])
swap(a[i],a[mark]);
}
}
void HeapAdjust(int a[],int s,int length)
{
int temp=a[s];
int child=2*s+1;
while(child<length)
{
if(child+1<length&&a[child]<a[child+1])
child++;
if(temp<a[child])
{
a[s]=a[child];
s=child;
child=2*s+1;
}
else
break;
}
a[s]=temp;
}
void BuildHeap(int a[],int length)
{
for(int i=length/2-1;i>=0;i--)
HeapAdjust(a,i,length);
}
void HeapSort(int a[],int length)
{
for(int i=length-1;i>0;i--)
{
BuildHeap(a,i);
swap(a[0],a[i]);
}
}
void main()
{
int a[10]={2,5,3,3,4,8,1,1,9,1};
mergesort(a,0,9);
for(int i=0;i<10;i++)
cout<<a[i]<<' ';
}
排序
最新推荐文章于 2022-04-29 23:24:15 发布