今天,我们一起用模板来写一个选择排序,熟练对模板的使用,具体如例1所示。
例1 选择排序-链表
ListSelectSort.hpp内容:
#ifndef _LIST_SELECT_SORT_H_ #define _LIST_SELECT_SORT_H_ template<typename T> struct Node { T m_Data; Node * m_pNext; }; template<typename T> bool SelectSort(Node<T> * & pHead) { Node<T> * pCurNode = NULL; Node<T> * pTemp = NULL; T tTemp; Node<T> * pMin = NULL; if (!pHead) return false; pCurNode = pHead; while (pCurNode) { pTemp = pCurNode->m_pNext; pMin = pCurNode; while (pTemp) { if (pTemp->m_Data < pMin->m_Data) { pMin = pTemp; } pTemp = pTemp->m_pNext; } if (pMin != pCurNode) { tTemp = pCurNode->m_Data; pCurNode->m_Data = pMin->m_Data; pMin->m_Data = tTemp; } pCurNode = pCurNode->m_pNext; } return true; } #endifmain.cpp内容:
#define CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #include "ListSelectSort.hpp" #include <time.h> #include <iostream> using namespace std; void main() { int i = 0; Node<int> * pInt = NULL; Node<int> * pNewNode = NULL; Node<int> * pCurNode = NULL; srand(time(NULL)); for (i = 0; i < 10; i++) { pNewNode = new Node<int>; if (pNewNode == NULL) { while (pInt) { pCurNode = pInt; pInt = pInt->m_pNext; delete pCurNode; } pInt = NULL; return; } pNewNode->m_Data = rand() % 100; pNewNode->m_pNext = pInt; pInt = pNewNode; } cout << "排序前:" << endl; pCurNode = pInt; while (pCurNode) { cout << pCurNode->m_Data << ' '; pCurNode = pCurNode->m_pNext; } cout << endl; if (SelectSort<int>(pInt) == false) { cout << "排序失败." << endl; } else { cout << "排序成功." << endl; } cout << "排序后:" << endl; pCurNode = pInt; while (pCurNode) { cout << pCurNode->m_Data << ' '; pCurNode = pCurNode->m_pNext; } cout << endl; while (pInt) { pCurNode = pInt; pInt = pInt->m_pNext; delete pCurNode; } pInt = NULL; _CrtDumpMemoryLeaks(); system("pause"); return; }运行效果如图1所示:
图1 运行效果
今天,我们一起实践了选择排序,希望能加深大家对模板的体会。