?总结了一下C语言常见的排序算法,包括
1,选择排序
2,插入排序
3,希尔排序
4,归并排序
5,快速排序
6,冒泡排序
7,堆排序
#include <stdio.h>
#include <stdlib.h>
/*选择排序算法*/
void selectSort(int *a,int n)
{
int i,j;
int tmp;
for(i=0; i<n-1; i++)
{
int min = i;
for(j = i+1; j<n; j++)
{
if(a[j] < a[min])
min = j;
}
if(min != i)
{
tmp = a[i];
a[i] = a[min];
a[min] = tmp;
}
}
}
/*插入排序*/
void insertSort(int *a, int n)
{
int i,j,temp;
for(i=1; i<n; i++)
{
temp = a[i];
for(j=i-1; j>=0; j--)
{
if(a[j] > temp)
a[j+1] = a[j];
else
break;
}
a[j+1] = temp;
}
}
/*希尔排序*/
void shellSort(int *a, int n)
{
int gap,i,j;
int temp;
for(gap=n/2;gap>0;gap/=2)
{
for(i=gap; i<n; i+=gap)
{
temp = a[i];
for(j=i-gap;j>=0;j-=gap)
{
if(a[j] > temp)
a[j+gap] = a[j];
else
break;
}
a[j+gap] = temp;
}
}
}
/*归并排序*/
void Merge(int *a, int low, int mid, int high)
{
int *b = (int*)malloc(10*sizeof(int));
int i,j,k=0;
for(i=low;i<=high;i++)
b[i] = a[i];
for(i=low,j=mid+1,k=i;i<=mid && j<=high;k++)
{
if(b[i] <= b[j])
{
a[k] = b[i];
i++;
}
else
{
a[k] = b[j];
j++;
}
}
while(i<=mid)
a[k++] = b[i++];
while(j<=high)
a[k++] = b[j++];
free(b);
}
void MergeSort(int *a, int low, int high)
{
if(low<high)
{
int mid = (low+high)/2;
MergeSort(a,low,mid);
MergeSort(a,mid+1,high);
Merge(a,low,mid,high);
}
}
/*快速排序*/
int getIndex(int *a, int low, int high)
{
int temp = a[low];
while(low<high)
{
while(low<high && a[high] > temp)
high--;
a[low] = a[high];
while(low<high && a[low] < temp)
low++;
a[high] = a[low];
}
a[low] = temp;
return low;
}
void quickSort(int *a, int low, int high)
{
if(low<high)
{
int index = getIndex(a,low,high);
quickSort(a,low,index-1);
quickSort(a,index+1,high);
}
}
/*冒泡排序*/
void bubbleSort(int *a, int n)
{
int i,j;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j] > a[j+1])
{
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
/*堆排序*/
void adjustHeap(int *a, int s, int n)
{
int rc = a[s];
int j;
for(j=2*s+1;j<n;j=2*j+1)
{
if(j+1<n && a[j] < a[j+1])
j++;
if(rc > a[j])
break;
a[s] = a[j];
s = j;
}
a[s] = rc;
}
void heapSort(int *a, int n)
{
int i,j;
for(i=n/2-1;i>=0;i--)
{
adjustHeap(a,i,n);
}
for(i=n-1;i>0;i--)
{
int temp = a[0];
a[0] = a[i];
a[i] = temp;
adjustHeap(a, 0, i);
}
}
void print(int *a, int n)
{
int i=0;
for(i=0; i<n; i++)
printf("%d ",a[i]);
printf("\n");
}
int main()
{
int a[] = {0,2,4,1,3,8,5,7,6,9};
//selectSort(a,10);
//insertSort(a,10);
//shellSort(a,10);
//MergeSort(a,0,9);
//quickSort(a,0,9);
//bubbleSort(a,10);
heapSort(a,10);
print(a,10);
}
|