声明待排序元素类型
1/*--------------------------
2typedef.h
3方便修改待排序元素类型
4-------------------------------------*/
5#ifndef TYPEDEF_H
6#define TYPEDEF_H
7
8typedef int T;
9
10#endif
2typedef.h
3方便修改待排序元素类型
4-------------------------------------*/
5#ifndef TYPEDEF_H
6#define TYPEDEF_H
7
8typedef int T;
9
10#endif
插入排序:
1/*---------------------------------------------------------------------------------------
2Insertion_sort.h
3直接插入排序
4对以数组形式给出的元素排序
5时间复杂度为(逆序数)N(N-1)/4 = O(N^2),并且在最坏情形下达到这个值
6最好情形下运行N次,最坏情形下运行2+3+…+N
7------------------------------------------------------------------------------------------------*/
8
9#ifndef INSERTION_SORT_H
10#define INSERTION_SORT_H
11
12#include "typedef.h"
13//直接插入排序
14void Insertion_sort(T *a, int n)
15{
16 for(int i = 1; i != n; ++i)
17 {
18 T temp = a[i];
19 int j = i - 1;
20 for(; j >= 0 && temp < a[j]; --j )
21 a[j + 1] = a[j];
22 a[j + 1] = temp;
23 }
24}
25
26#endif
2Insertion_sort.h
3直接插入排序
4对以数组形式给出的元素排序
5时间复杂度为(逆序数)N(N-1)/4 = O(N^2),并且在最坏情形下达到这个值
6最好情形下运行N次,最坏情形下运行2+3+…+N
7------------------------------------------------------------------------------------------------*/
8
9#ifndef INSERTION_SORT_H
10#define INSERTION_SORT_H
11
12#include "typedef.h"
13//直接插入排序
14void Insertion_sort(T *a, int n)
15{
16 for(int i = 1; i != n; ++i)
17 {
18 T temp = a[i];
19 int j = i - 1;
20 for(; j >= 0 && temp < a[j]; --j )
21 a[j + 1] = a[j];
22 a[j + 1] = temp;
23 }
24}
25
26#endif
直接选择排序:
1/*----------------------------------------------
2DirectSelection_sort.h
3直接选择排序
4时间复杂度O(N^2)
5--------------------------------------------------------*/
6#ifndef DIRECTSELECTION_SORT_H
7#define DIRECTSELECTION_SORT_H
8
9#include "typedef.h"
10#include "swap.h"
11
12//直接选择法排序
13void DirectSelection_sort(T*a, int n)
14{
15 for(int i = 0; i != n; ++i)
16 {
17 int k = i;
18 for(int j = i; j != n; ++j)
19 if(a[j] < a[k]) k = j;
20 swap(a[k],a[i]);
21 }
22}
23
24#endif
2DirectSelection_sort.h
3直接选择排序
4时间复杂度O(N^2)
5--------------------------------------------------------*/
6#ifndef DIRECTSELECTION_SORT_H
7#define DIRECTSELECTION_SORT_H
8
9#include "typedef.h"
10#include "swap.h"
11
12//直接选择法排序
13void DirectSelection_sort(T*a, int n)
14{
15 for(int i = 0; i != n; ++i)
16 {
17 int k = i;
18 for(int j = i; j != n; ++j)
19 if(a[j] < a[k]) k = j;
20 swap(a[k],a[i]);
21 }
22}
23
24#endif