本文内容
- 通用数据结构
- 直接插入排序
- 冒泡排序
- Main 函数
- 运行结果
本文用 CodeBlock 编写。同时也提供 VS C 和 VS C# 代码。
通用数据结构
- MyElement.h
#ifndef MYELEMENT_H_INCLUDED
#define MYELEMENT_H_INCLUDED
#define LT(a,b) ((a)<(b))
#define TRUE 1
#define FALSE 0
typedef int Status;
typedef int ElementType;
void Print(ElementType e[], int n);
#endif // MYELEMENT_H_INCLUDED
- MyElement.c
#include
#include "MyElement.h"
void Print(ElementType e[], int n)
{
int i;
for(i=0; i
printf("%d ",e[i]);
printf("\n");
}
直接插入排序
- InsertSort.h
#ifndef INSERTSORT_H_INCLUDED
#define INSERTSORT_H_INCLUDED
#include "MyElement.h"
void InsertSort(ElementType e[], int n);
void Main_InsertSort();
#endif // INSERTSORT_H_INCLUDED
- InsertSort.c
#include
#include "MyElement.h"
#include "InsertSort.h"
#define N 11
void InsertSort(ElementType a[], int n)
{
int i,j;
for(i=2; i<=n-1; ++i)
if (LT(a[i],a[i-1]))
{
a[0] = a[i];
for(j=i-1; LT(a[0],a[j]); --j)
a[j+1] = a[j];
a[j+1] = a[0];
}
}
void Main_InsertSort()
{
ElementType e[N] = {0,49,38,65,97,76,13,27,49,55,10};
printf("Before InsertSort:\n");
Print(e,N);
InsertSort(e,N);
printf(" After InsertSort:\n");
Print(e,N);
}
冒泡排序
- BubbleSort.h
#ifndef BUBBLESORT_H_INCLUDED
#define BUBBLESORT_H_INCLUDED
#include "MyElement.h"
void BubbleSort(ElementType e[], int n);
void Main_BubbleSort();
#endif // BUBBLESORT_H_INCLUDED
- BubbleSort.c
#include
#include "MyElement.h"
#include "BubbleSort.h"
#define N 10
void BubbleSort(ElementType a[], int n)
{
int i,j,t;
Status change;
for(i=n-1,change=TRUE; i>0 && change; --i)
{
change=FALSE;
for(j=0; j
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
change=TRUE;
}
}
}
void Main_BubbleSort()
{
int d[N]= {50,38,65,97,76,13,27,49,55,4};
printf("Before BubbleSort:\n");
Print(d, N);
BubbleSort(d, N);
printf(" After BubbleSort:\n");
Print(d,N);
}
参看。
Main 函数
#include "BubbleSort.h"
#include "InsertSort.h"
int main()
{
Main_InsertSort();
Main_BubbleSort();
}
运行结果