1.前言
自从大一学过一点点的c++之后,后面一直用java,未得机会去训练c++。
有时候觉得java不够带感,偶然想写一个简单的c/c++排序,都不会写!
尚未晚矣,从头开始。。。
准备先用c++把所有的排序实现一遍。
本节来看最简单粗暴的插入排序。
2.插入排序(insertion sort)
2.1简单介绍
插入排序,通过将所有的元素执行一遍插入之后即完成排序。在每一次的插入,前面插入的元素已经排好序,新来的元素则要跟已排好序的元素进行比较,找到它的位置。之后,将位置以及后面的元素后移一位,将新来的元素插入合适的位置。
2.2代码实现
原理简单,下面用c++实现:
.h:声明定义插入排序Insert_Sorting模板类
#ifndef INSERTSORTING_H
#define INSERTSORTING_H
//
template <class Type> class Insert_Sorting{ //template class
private:
Type *dataArray; //dynamic data array
int maxNum; //max array size
int current; //actual array size less than max
public:
Insert_Sorting();
Insert_Sorting(int num);
~Insert_Sorting();
//
int compare(const Type element1, const Type element2); //
//模板只能用于定义数据类型时用,因此对于过程,模板不能代替。因此对于不同类型的文件的读取,分开写了。。。
void read_data_INT (const char * fileName); //read INT data from file
void read_data_DOUBLE (const char * fileName); //DOUBLE
void read_data_STR (const char * fileName); //STRING
void sort (); //insertion sort
void display (); //display
};
#endif
.cpp:对模板类的成员函数的实现
#include "insertSorting.h"
#include "stdlib.h"
#include <iostream>
#include <fstream>
using namespace std;
template <class Type> Insert_Sorting<Type>::Ins