堆排序
#include <stdio.h>
void mySwap(int *a , int i , int j) //½«Á½Êý½»»»
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
//调整堆
void heapify(int *a , int index , int len)
{
int lindex = 2*index + 1; //左孩子结点下标
int rindex = 2*index + 2; //右孩子结点下标
int max = index;
if (lindex < len && a[max] < a[lindex])
max = lindex;
if (rindex < len && a[max] < a[rindex])
max = rindex;
if (max != index)
{
mySwap(a , max , index);
heapify(a , max , len); //递归调整
}
}
void mySort(int *a , int len)
{
//建堆:从非叶节点开始,把每一个结点调整为大顶堆
int i ;
for (i = len/2 - 1 ; i >= 0 ; i--)
{
heapify(a , i , len);
}
//排序
int count = len;
for(i = len-1 ; i >= 0 ; i--)
{
mySwap(a , 0 , i); //堆顶元素和当前堆最后一个元素进行交换
count--;
heapify(a , 0 , count);
}
}
void myPrint(int *a , int len)
{
int i;
for(i = 0 ; i < len ; i++)
{
printf("%4d",a[i]);
}
printf("\n");
}
int main()
{
int a[] = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
int len = sizeof(a)/sizeof(a[0]);
mySort(a , len);
myPrint(a , len);
return 0;
}
归并排序
#include <stdio.h>
void mySwap(int *a , int i , int j) //½«Á½Êý½»»»
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
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[i++];
else
tmp[k++] = a[j++];
}
while(i <= mid)
{
tmp[k++] = a[i++];
}
while(j <= right)
{
tmp[k++] = a[j++];
}
for(i = 0 ; i < k ; i++)
{
a[left+i] = tmp[i];
}
}
void mergeSort(int *a , int left , int right , int *tmp)
{
int mid = (left + right)/2;
if(left < right)
{
mergeSort(a , left , mid , tmp); //对左边数组进行归并排序
mergeSort(a , mid+1 , right , tmp); //对右边数组进行归并排序
merge(a , left , mid , right , tmp); //合并左右两个数组
}
}
void myPrint(int *a , int len)
{
int i;
for(i = 0 ; i < len ; i++)
{
printf("%4d",a[i]);
}
printf("\n");
}
int main()
{
int a[] = {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);
myPrint(a , len);
return 0;
}