排序算法-中级篇

    技术2025-06-21  12

    排序算法-中级篇

    上一篇文章中我回顾了在学习入门计算机语言时最初接触的排序算法(冒泡排序,选择排序),不管是冒泡排序还是选择排序,它们的效率都不高时间复杂度都为O(n^2),对于大规范的数据出来是不能接受了,因而就需要更高效的排序算法。在这里我回顾一下我们在数据结构与算法这门课学习到的堆排序(O(nlog(n))),算法逻辑我就不赘述了,大家都知道。

    代码实现上我是用C++的函数模板来实现。

    实现代码如下:

    /* FileName: qsort.cpp Author: ACb0y Date Time: 2011年2月13日12:36:19 Last modify Time: 2011年2月13日16:55:23 */ #include <iostream> using namespace std; typedef char * str; /* 函数名: template<class type> void swap(type * lv, type * rv); 功能: 交换lv和rv指向的变量的值。 参数: lv (in): type *: 左值 rv (in): type *: 右值 返回值: 无 */ template<class type> void swap(type * lv, type * rv) { type tmp = *lv; *lv = *rv; *rv = tmp; } /* 函数名: template<class type> int partition(type * data, int left, int right, bool cmp(const type & lv, const type & rv)) 功能: 对指定区域的元素序列进行划分,以指定序列中的最后一个元素为基准 是的它左边的值都比它小,右边的值都比他大。 参数: data (in): type *: 指向元素序列的头指针。 left (in): int: 左边界 right (in): int: 右边界 cmp: 如何比较元素的函数谓词 返回值: pos :基准元素划分后在区间的位置 */ template<class type> int partition(type * data, int left, int right, bool cmp(const type & lv, const type & rv)) { int pos = left; for (int i = left; i < right; ++i) { if (cmp(data[i], data[right])) { swap(&data[i], &data[pos]); pos++; } } swap(&data[right], &data[pos]); return pos; } /* 函数名: template<class type> void qsortVersionOne(type * data, int left, int right, bool cmp(const type & lv, const type & rv)); 功能:堆排序 参数: data (in): char *:元素序列的头指针 left (in): int: 左边界 right (in): int: 右边界 cmp (in): bool (const type &, const type &): 元素比较函数谓词 返回值:无 */ template<class type> void qsortVersionOne(type * data, int left, int right, bool cmp(const type & lv, const type & rv)) { if (left < right) { int pos = partition(data, left, right, cmp); qsortVersionOne(data, left, pos - 1, cmp); qsortVersionOne(data, pos + 1, right, cmp); } } /* 函数名: template<class type> void print(type * data, int n, char * format); 功能:输出元素序列中的指定个数的元素 参数: data (in): type *: 元素序列头元素的指针 n (in): int :要输出的元素的个数 format (in): char *: 输出格式 返回值:无 */ template<class type> void print(type * data, int n, char * format) { for (int i = 0; i < n; ++i) { printf(format, data[i]); } printf("/n"); } /* 函数名:bool cmp_int(const int & lv, const int & rv); 功能:整数数据比较的函数谓词 参数: lv (in): const int&: 左值 rv (in): const int&: 右值 返回: true: lv < rv false: lv >= rv */ bool cmp_int(const int & lv, const int & rv) { if (lv < rv) { return true; } return false; } /* 函数名:bool cmp_str(const str & lv, const str & rv); 功能:整数数据比较的函数谓词 参数: lv (in): const str &:左值 rv (in): const str &: 右值 返回: true: lv < rv false: lv >= rv */ bool cmp_str(const str & lv, const str & rv) { if (strcmp(lv, rv) < 0) { return false; } return true; } int main() { int data[10] = {1, 3, 4, 5, 2, 7, 10, 8, 9}; qsortVersionOne(data, 0, 9, cmp_int); print(data, 10, "%d "); str strData[5] = {"class", "interface", "component", "package", "object-class"}; qsortVersionOne(strData, 0, 4, cmp_str); print(strData, 5, "%s "); return 0; }  

    运行结果:

     

    最新回复(0)