void swap(int a[],int i,int j)
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
void printfA(int a[],int len)
{
int i;
for(i = 0;i < len;i++)
{
printf("%4d",a[i]);
}
printf("\n");
}
1、堆排序
//堆排序
void heapify(int *a,int i,int len)
{
int left = 2 * i + 1;
int right = 2 * i + 2;
int max = i;
if(left < len && a[left] > a[max])
max = left;
if(right < len && a[right] > a[max])
max = right;
if(max != i)
{
swap(a,i,max);
heapify(a,max,len);
}
}
void heapsort(int *a,int len)
{
int i;
for(i = len / 2 - 1;i >= 0;i--)
{
heapify(a,i,len);
}
for(i = len - 1;i > 0;i--)
{
swap(a,i,0);
heapify(a,0,--len);
}
}
int main()
{
int a[10] = {9,8,7,6,5,4,3,2,1,0};
int len = sizeof(a) / sizeof(a[0]);
heapsort(a,len);
printfA(a,len);
return 0;
}
2、归并排序
//归并排序
void merge(int *a,int left,int mid,int right,int *tmp)
{
int i = left;
int j = mid + 1;
int k = 0;
while(i <= mid && j <= right)
{
if(a[i] > a[j])
tmp[k++] = a[j++];
else
tmp[k++] = a[i++];
}
while(i <= mid)
tmp[k++] = a[i++];
while(j <= mid)
tmp[k++] = a[j++];
k = 0;
for(i = left;i <= right;i++)
{
a[i] = tmp[k++];
}
}
void mergesort(int *a,int left,int right,int *tmp)
{
if(left >= right)
return;
int mid = (left + right) / 2;
mergesort(a,left,mid,tmp);
mergesort(a,mid + 1,right,tmp);
merge(a,left,mid,right,tmp);
}
int main()
{
int a[10] = {9,8,7,6,5,4,3,2,1,0};
int len = sizeof(a) / sizeof(a[0]);
int tmp[10];
mergesort(a,0,len - 1,tmp);
printfA(a,len);
return 0;
}
3、快速排序
//快速排序
int partition(int *a,int left,int right)
{
int pivot = a[right];
int index = left;
int i;
for(i = left;i < right;i++)
{
if(a[i] < pivot)
{
swap(a,i,index);
index++;
}
}
swap(a,index,right);
return index;
}
void qsort(int *a,int left,int right)
{
if(left < right)
{
int pivot = partition(a,left,right);
qsort(a,left,pivot - 1);
qsort(a,pivot + 1,right);
}
}
int main()
{
int a[10] = {9,8,7,6,5,4,3,2,1,0};
int len = sizeof(a) / sizeof(a[0]);
qsort(a,0,len -1);
printfA(a,len);
return 0;
}