冒泡排序、快速排序、选择排序、堆排序、桶排序、插入排序。
Main.c
#include <time.h>
#include "MySort.h"
#define N 10
typedef int Int_D;
void main()
{
Int_D Array[N] = { 0};
srand((unsigned int)time(NULL));
for (int i = 0; i < N; i++)
{
Array[i] = rand() % 100;
}
Show(Array,N);
InsertSort(Array, N);
Show(Array, N);
system("pause");
}
MySort.h
#pragma once
#ifdef __cplusplus
extern "C"
{
#endif
#include <stdio.h>
#include <memory.h>
#include <stdlib.h>
typedef int D_Type;
void Show(D_Type* Array, int Count);
void Swap(D_Type* a, D_Type* b);
void FindMax(D_Type* Array, int Count);
void BubbleSort(D_Type* Array, int Count);
void QuickSort(D_Type* Array, int Left,int Right);
void SelectSort(D_Type* Array, int Count);
void HeapSort(D_Type* Array, int Count);
void BucketSort(D_Type* Array, int Count);
void InsertSort(D_Type* Array, int Count);
#ifdef __cplusplus
}
#endif
MySort.c
#include "MySort.h"
void Show(D_Type* Array, int Count)
{
for (int i = 0; i < Count; i++)
{
printf("%5d", Array[i]);
}
puts("");
}
void Swap(D_Type* a, D_Type* b)
{
D_Type Temp = *a;
*a = *b;
*b = Temp;
}
void FindMax(D_Type* Array, int Count)
{
for (int i = Count - 1; i > 0; i--)
{
int Parent = i / 2;
int Child = i + 1;
if (Array[Child] < Array[Child - 1])
{
Child--;
}
if (Array[Child]>Array[Parent])
{
Swap(&Array[Child], &Array[Parent]);
}
}
}
void BubbleSort(D_Type* Array, int Count)
{
for (int i = 0; i < Count - 1; i++)
{
for (int j=0; j < Count - 1 - i; j++)
{
if (Array[j] < Array[j+1])
{
Swap(&Array[j], &Array[j + 1]);
}
}
}
}
void QuickSort(D_Type* Array, int Left, int Right)
{
if (Left < Right)
{
int i = Left;
for (int j = i + 1; j <= Right;j++)
{
if (Array[Left] < Array[j])
{
i++;
Swap(&Array[i], &Array[j]);
}
}
Swap(&Array[i], &Array[Left]);
QuickSort(Array, Left, i - 1);
QuickSort(Array, i + 1, Right);
}
}
void SelectSort(D_Type* Array, int Count)
{
int Max = 0;
for (int i = 0; i < Count-1; i++)
{
Max = i;
for (int j = i+1; j < Count; j++)
{
if (Array[Max] < Array[j])
{
Max = j;
}
}
if (Max != i)
{
Swap(&Array[i],&Array[Max]);
}
}
}
void HeapSort(D_Type* Array, int Count)
{
for (int i = 0; i < Count; i++)
{
FindMax(Array + i, Count - i);
}
}
void BucketSort(D_Type* Array, int Count)
{
FindMax(Array, Count);
D_Type MaxVal = Array[0] + 1;
D_Type* Bucket = (D_Type*)malloc(sizeof(D_Type)*MaxVal);
memset(Bucket, 0, sizeof(D_Type)*MaxVal);
for (int i = 0; i < MaxVal; i++)
{
Bucket[i] = MaxVal;
}
for (int i = 0; i < Count; i++)
{
Bucket[Array[i]] = Array[i];
}
int Num = 0;
for (int i = 0; i < MaxVal; i++)
{
if (Bucket[i] != MaxVal)
{
Array[Num] = Bucket[i];
Num++;
}
}
free(Bucket);
Bucket=NULL;
}
void InsertSort(D_Type* Array, int Count)
{
for (int i = 1; i < Count; i++)
{
D_Type Temp = Array[i];
int j = i;
while (j>0 && Array[j - 1] > Temp)
{
Array[j] = Array[j - 1];
j--;
}
Array[j] = Temp;
}
}