冒泡 时间复杂度 n*(n-1)/2 空间复杂度 1;
void sortint(int * a, int count)
{
for(int
top
= 0;
top
<count
;
top
++)
for(int
seek
=
top
+1;
seek
<count;
seek++)
if(*(a+
top
) > *(a+
seek
))
{
int tem = *(a+
top
);
*(a+
top
) = *(a+
seek
);
*(a+
seek
) = tem;
}
};
插入 时间复杂度n*(n-1)/2 空间复杂度 1;
void insertsort(int a[],int num)
{
for(int seek =1 ; seek < num; seek++)
{
int get = a[seek];
int front = seek-1;
while(front > 0&&a[front] > get)
{
a[front+1] = a[front];
front--;
}
a[front+1] = get;
}
}
快速排序 时间复杂度nlogn 空间复杂度1
int partition(int a[],int left ,int right)
{
int pri = a[right];
int tail = left-1;
for(int seek = left;seek<right;seek++)
{
if(a[seek]<pri)
{
swap(a,seek,++tail);
}
}
swap(a,++tail,right);
return tail;
}
void sortint1(int a[] ,int left ,int right)
{
if(left >= right)
return;
int prs = partition(a,left,right);
sortint1(a,left,prs-1);
sortint1(a,prs+1,right);
}
堆排序 时间复杂度nlogn 空间复杂度 1
void heapify(int a[],int i ,int size)
{
int left_child = 2*i+1;
int right_child = 2*i+2;
int max = i;
if(left_child<size&&a[left_child]>a[max])
max = left_child;
if(right_child<size&&a[right_child]>a[max])
max =right_child;
if(max != i)
{
swap(a,i,max);
heapify(a,max,size);
}
}
void heapsort(int a[], int size)
{
for(int i = size/2-1;i>=0;i--)
heapify(a,i,size);
while(size>1)
{
swap(a,0,--size);
heapify(a,0,size);
}
}
归并算法 时间复杂度nlogn 空间复杂度 n
void mergea(int a[],int left,int mid,int right,int d[])
{
int lbegin = left;
int rbegin = mid+1;
int index = left;
int len = right- left +1;
int *temp = new int[len];
for(int hh = 0;hh<len;hh++)
temp[hh] = 1;
int ind =0;
while(lbegin<=mid&&rbegin<=right)
{
d[index++] = a[lbegin]<= a[rbegin]?a[lbegin++]:a[rbegin++];
//temp[ind++] = a[lbegin]<= a[rbegin]?a[lbegin++]:a[rbegin++];
}
while (lbegin<=mid)
{
d[index++] = a[lbegin++];
//temp[ind++] = a[lbegin++];
}
while (rbegin<=right)
{
d[index++] = a[rbegin++];
//temp[ind++] = a[rbegin++];
}
for(int i = left;i<=right;i++)
{
a[i] = d[i];
//a[i] = temp[i-left];
}
}
void mergea1(int a[],int len,int d[])
{
int left,mid,right;
for(int i =1 ;i<len;i++)
{
left = 0;
while(left +i <len)
{
mid = left + i -1;
right = mid +i < len? mid+i:len-1;
mergea(a,left,mid,right,d);
left = right +1;
}
}
}
void mergsort(int a[], int left , int right,int d[])
{
if(left == right)
return;
int mid = (left+right)/2;
mergsort(a,left,mid,d);
mergsort(a,mid+1,right,d);
mergea(a,left,mid,right,d);
}