#include <stdio.h>
#define LEN 10
void bubble_sort(int *,int);
void selection_sort(int *,int);
void insertion_sort(int *,int);
void shell_sort(int *,int);
void binary_insertion_sort(int *,int);
void heap_sort(int *,int);
void merge_sort(int *,int,int);
void quick_sort(int *,int,int);
int main(void)
{
int i;
int v[LEN] = {5,2,8,7,4,3,1,0,6,9};
// bubble_sort(v,LEN);
// selection_sort(v,LEN);
// insertion_sort(v,LEN);
// binary_insertion_sort(v,LEN);
shell_sort(v,LEN);
// heap_sort(v,LEN);
// merge_sort(v,0,LEN-1);
// quick_sort(v,0,LEN-1);
for(i=0;i<LEN;i++)
printf("%4d",v[i]);
getch();
return 0;
}
void swap(int * v,int,int);
/*冒泡排序*/
void bubble_sort(int * v,int n)
{
int i,j;
for(i=0;i<n;i++)
for(j=0;j<n-1;j++)
if(*(v+j)>*(v+j+1))
swap(v,j,j+1);
}
/*选择排序*/
void selection_sort(int * v,int n)
{
int i,j;
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(*(v+j)<*(v+i))
swap(v,i,j);
}
/*插入排序*/
void insertion_sort(int * v,int n)
{
int i,j;
for(i=1;i<n;i++)
for(j=i;j>0 && *(v+j-1)>*(v+j);j--)
swap(v,j-1,j);
}
/*二分插入排序*/
void binary_insertion_sort(int * v,int n)
{
int i,j,low,mid,high;
for(i=1;i<n;i++)
{
low=0;
high=i-1;
while(low<=high)
{
mid=(low+high)/2;
if(*(v+i)<*(v+mid))
high=mid-1;
else
low=mid+1;
}
for(j=i-1;j>=low;j--)
swap(v,j+1,j);
}
}
/*希尔排序*/
void shell_sort(int * v,int n)
{
int i,j,gap;
for(gap=n/2;gap>0;gap/=2)
for(i=gap;i<n;i++)
for(j=i-gap;j>=0 && *(v+j)>*(v+j+gap);j-=gap)
swap(v,j,j+gap);
}
void heap_adjust(int *,int,int);
/*堆排序*/
void heap_sort(int * v,int n)
{
int i,j;
for (i=n/2-1;i>=0;i--)
heap_adjust(v,i,n);
for (j=n-1;j>0;j--)
{
swap(v,0,j);
heap_adjust(v,0,j);
}
}
/*创建大根堆*/
void heap_adjust(int * v,int parent,int length)
{
int child;
while(2*parent+1<length)
{
child = 2*parent;
if (child<length-1 && *(v+child+1)> *(v+child))
++child;
if (*(v+parent) < *(v+child))
swap(v,parent,child);
else
break;
parent=child;
}
}
int temp[LEN];
void merge(int *,int,int,int);
/*归并排序*/
void merge_sort(int * v,int low,int high)
{
if(low<high)
{
int mid=(low+high)/2;
merge_sort(v,low,mid);
merge_sort(v,mid+1,high);
merge(v,low,mid,high);
}
}
void merge(int * v,int low,int mid,int high)
{
int i=low,j=mid+1,k=low;
while(i<=mid&&j<=high)
if(*(v+i) <= *(v+j))
*(temp+k++)=*(v+i++);
else
*(temp+k++)=*(v+j++);
while(i<=mid)
*(temp+k++)=*(v+i++);
while(j<=high)
*(temp+k++)=*(v+j++);
for(i=low;i<=high;i++)
*(v+i)=*(temp+i);
}
/*快速排序*/
void quick_sort(int * v,int left,int right)
{
if(left>=right)
return;
int key,i;
key=left;
for(i=left+1;i<=right;i++)
if(*(v+i)<*(v+left))
swap(v,++key,i);
swap(v,left,key);
quick_sort(v,left,key-1);
quick_sort(v,key+1,right);
}
/*交换数组元素*/
void swap(int * v,int i,int j)
{
int temp;
temp = *(v+i);
*(v+i) = *(v+j);
*(v+j) = temp;
}
C语言之排序算法
最新推荐文章于 2024-02-01 11:40:08 发布