数据结构——直接插入排序(c++)
2015-06-21 20:21
603 查看
ImprovedInsertSorter.h
Sorter.h
ImprovedInsertSort.cpp
//ImprovedInsertSorter.h //优化的插入排序类 #if !defined(AFX_ImprovedInsertSorter) #define AFX_ImprovedInsertSorter #include "Sorter.h" template <class Record> class ImprovedInsertSorter:public Sorter<Record> { public: void Sort(Record Array[],int n); }; //优化的插入排序,Array[]为待排序数组,n为数组长度 template <class Record> void ImprovedInsertSorter<Record>::Sort(Record Array[], int n) { Record TempRecord; int i,j; for(i=1;i<n;i++) { TempRecord=Array[i]; j=i-1; while(j>=0 && TempRecord<Array[j]) { Array[j+1]=Array[j]; j=j-1; } Array[j+1]=TempRecord; } } #endif
Sorter.h
//Sorter.h #if !defined(AFX_Sorter) #define AFX_Sorter //总排序类 template <class Record> class Sorter{ protected: static void swap(Record Array[],int i,int j); //交换数组中的两个记录 public: virtual void Sort(Record Array[],int n)=0; //对数组Array进行排序 void PrintArray(Record array[], int n); //输出数组内容 }; //交换数组中的两个记录 template <class Record> void Sorter<Record>::swap(Record Array[],int i,int j) { Record TempRecord = Array[i]; Array[i] = Array[j]; Array[j] = TempRecord; } //输出数组内容 template <class Record> void Sorter<Record>::PrintArray(Record Array[], int n) { for(int i=0;i<n;i++) cout<<Array[i]<<" "; cout<<endl; } #endif
ImprovedInsertSort.cpp
//ImprovedInsertSort.cpp //优化的直接插入排序 #include <iostream.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "ImprovedInsertSorter.h" const int N=1000; // 设定随即函数的种子 inline void Randomize() { srand(1); } //返回一个0到n-1之间的随机数 inline int Random(int n) { return rand() % (n); } void main() { ImprovedInsertSorter<int> c; srand(1); int Array[8]; for(int i=0;i<8;i++) { Array[i]=Random(100); } c.Sort(Array,8); c.PrintArray(Array,8); }
相关文章推荐
- 数据结构——二叉树2(c++)
- 词典的实现(3)--使用JAVA类库ArrayList实现Map数据结构
- 数据结构——二叉树1(c++)
- Java数据结构系列——简单排序:泡、选择、直接进入
- 数据结构基础
- 二叉树学习笔记 分类: C/C++ 数据结构与算法 2015-06-21 12:00 36人阅读 评论(0) 收藏
- 数据结构实验之二叉树的建立与遍历
- 数据结构实验之二叉树的建立与遍历 分类: 树 2015-06-21 11:02 8人阅读 评论(0) 收藏
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历 分类: 树 2015-06-21 10:58 11人阅读 评论(0) 收藏
- [数据结构]八皇后(暴力,解答树,DFS回溯)
- 二叉树的三种遍历方式:递归、栈、循环 分类: C/C++ 数据结构与算法 2015-06-21 09:47 269人阅读 评论(0) 收藏
- JAVA 常用数据结构操作
- 数据结构和算法-010 数组排序 希儿排序
- [数据结构]埃及分数(暴力,解答树,迭代加深搜索)
- [数据结构]二叉树自学
- 线性表子系统
- 数据结构第三部分:树与树的表示、二叉树及其遍历、二叉搜索树、平衡二叉树、堆、哈夫曼树、集合及其运算
- 数据结构——链式队列(c++)
- 斐波那契查找(超详解)