#include<stdio.h>
#include<stdlib.h>
void Print(int a[], int n);
void Swap (int *a, int *b);
int main()
{
int a[20] = {21,23,53,32,54,30,65,43,13,35,24,95,65,67,45,87,37,22,100,64};
Print(a, 20);
BubbleSort(a, 20);
InsertSort1(a, 20);
SimpleSelectSort(a,20);
ShellSort(a, 20);
QuickSort(a, 20);
printf("\n排序结果:\n");
Print(a, 20);
return 0;
}
void Print(int a[], int n)//数组输出函数。便于调试
{
for(int i = 0; i < n; i++)
printf("%4d", a[i]);
}
void Swap (int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
冒泡排序:
/************************冒泡排序法***********************/
void BubbleSort(int a[],int n)
{
for(int i = 0; i < n; i++)
for(int j = 1; j < n - i ; j++)
{
if(a[j] > a[j-1])
Swap(&a[j], &a[j-1]);
}
}
简单选择排序:
/***************简单选择排序******************************/
void SimpleSelectSort(int a[],int n)
{
int min;
for(int i = 0; i < n; i++)
{
min = i;
for(int j = i + 1 ; j < n; j++)
{
if(a[j] > a[min])
min = j;
}
if(min != i)
Swap(&a[min], &a[i]);
}
}
直接插入排序:
void InsertSort1(int a[], int n)
{
int i, j;
for( i = 1; i < n; ++i)
{
for(j = i-1; j >= 0; --j)
{
if(a[j] < a[i])
break;
}
if(j != i - 1)
{
int temp = a[i];
for(int k = i-1;k > j; --k)
a[k+1] = a[k];
a[k+1] = temp;
}
}
}
希尔排序:
void ShellSort(int a[], int n)
{
int i, j, step;
for(step = n/2; step > 0; step/=2)
{
for(i = 0; i < step; i++)
{
for(j = i+step; j < n; j += step)
{
if(a[j] < a[j-step])
{
int temp = a[j];
int k = j - step;
while( k >= 0 && a[k] > temp)
{
a[k + step] = a[k];
k = k - step;
}
a[k + step] = temp;
}
}
}
}
}
归并排序:
/*******************归并排序开始*************************/
void MergeSort(int a[], int n)
{
int *b = (int*)malloc(sizeof(int));
MergeSortAssist(a, b, 0, n-1);
for(int i = 0; i < n; i++)
a[i] = b[i];
free(b);
}
void MergeSortAssist(int a[], int b[], int first,int last)
{
while(first < last)
{
int mid = (last + first)/2;
MergeSortAssist(a, b, first, mid);
MergeSortAssist(a, b, mid + 1, last);
MergeSortMsort(a, b, first, mid, last);
}
}
void MergeSortMsort(int a[], int b[], int first, int mid, int last)
{
int i = first;
int j = mid + 1;
int k = 0;
while( i <= mid && j <= last)
{
if(a[i] <= a[j])
b[k++] = a[i++];
else
b[k++] = a[j++];
}
while( j<= last)
b[k++] = a[j++];
while( i <= mid)
b[k++] = a[i++];
for(int l = first; l < k; l++)
a[first + l] = b[l];
}
/*****************归并排序结束*********************/
快速排序:
/*******************快速排序开始***********************/
void QuickSort(int a[], int n)
{
Qsort(a, 0, n-1);
}
void Qsort(int a[], int low, int high)
{
int pivot;
if( low < high)
{
pivot = Partition(a, low, high);
Qsort(a, low, pivot-1);
Qsort(a, pivot + 1, high);
}
}
int Partition(int a[], int low, int high)
{
int i = low, j = high;
int temp = a[low];
while(i < j)
{
while(i < j && a[j] >= temp)
j--;
if(i < j)
{
a[i] = a[j];
i++;
}
while(i < j && a[i] < temp)
i++;
if(i < j)
{
a[j] = a[i];
j--;
}
}
a[i] = temp;
return i;
}
/*******************快速排序结束*************************/
参考: 1 大话数据结构
2 http://blog.csdn.net/column/details/algorithm-easyword.html