1、归并排序
#include<stdio.h>
#include<stdlib.h>

typedef int DataType;


void merge(DataType arr[], int low, int mid, int high)
{
DataType *arrTmp;
arrTmp = (DataType *)malloc(sizeof(DataType)*(high-low+1));
if(arrTmp==NULL)return;

int i=low, j=mid+1, p=0;

while(i<=mid&&j<=high)
{
arrTmp[p++] = arr[i]<arr[j]?arr[i++]:arr[j++];
}

while(i<=mid)
{
arrTmp[p++] = arr[i++];
}

while(j<=high)
{
arrTmp[p++] = arr[j++];
}
p = 0;

while(p<high-low+1)
{
arr[low+p] = arrTmp[p];
p++;
}
free(arrTmp);
arrTmp = NULL;
}


void merge_sort(DataType arr[], int low, int high)
{
int mid;

if(low<high)
{
mid = (low+high)/2;
merge_sort(arr, low, mid);
merge_sort(arr, mid+1, high);
merge(arr, low, mid, high);
}
}

#define DATA_NUM 10

void main()
{

DataType a[DATA_NUM] =
{3, 5, 1, 43, 53, 4, 12, 9, 30, 11};
int i = 0;
merge_sort(a, 0, DATA_NUM-1);

while(i<DATA_NUM)
{
printf("%d ", a[i++]);
}
printf("\n");
}2、快速排序
#include<stdio.h>
#include<stdlib.h>

typedef int DataType;


void swap(DataType *a, DataType *b)
{
DataType tmp;
tmp = *a;
*a = *b;
*b = tmp;
}


int quick(DataType arr[], int low, int high)
{
int pivot = arr[low];

while(low<high)
{

while(low<high&&arr[high]>pivot)
{
high--;
}
swap(&arr[low], &arr[high]);

while(low<high&&arr[low]<pivot)
{
low++;
}
swap(&arr[low], &arr[high]);
}
return low;
}


void quick_sort(DataType arr[], int low, int high)
{
int mid;

if(low<high)
{
mid = quick(arr, low, high);
quick_sort(arr, low, mid-1);
quick_sort(arr, mid+1, high);
}
}

#define DATA_NUM 10

void main()
{

DataType a[DATA_NUM] =
{3, 5, 1, 43, 53, 4, 12, 9, 30, 11};
int i = 0;
quick_sort(a, 0, DATA_NUM-1);

while(i<DATA_NUM)
{
printf("%d ", a[i++]);
}
printf("\n");
}3、冒泡排序
#include<stdio.h>
#include<stdlib.h>

typedef int DataType;


void swap(DataType *a, DataType *b)
{
DataType tmp;
tmp = *a;
*a = *b;
*b = tmp;
}


void bubble_sort(DataType arr[], int length)
{
int pos, j=0;
int high = length-1;

while(high>0)
{
pos = high;
high = 0;

for(j=0; j<pos; j++)
{

if(arr[j]>arr[j+1])
{
swap(&arr[j], &arr[j+1]);
high = j;
}
}
}
}

#define DATA_NUM 10

void main()
{

DataType a[DATA_NUM] =
{3, 5, 1, 43, 53, 4, 12, 9, 30, 11};
int i = 0;
bubble_sort(a, DATA_NUM);

while(i<DATA_NUM)
{
printf("%d ", a[i++]);
}
printf("\n");
}
posted @
2009-10-13 22:22
千年
阅读(
443)
评论()
编辑
收藏
举报
点击右上角即可分享
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步