鱼C论坛

 找回密码
 立即注册
查看: 2791|回复: 0

[技术交流] Combsort(使用G++4.8.1)

[复制链接]
发表于 2014-2-9 14:38:23 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
用的是我自己的iostream,所以包含的头文件多一点。如果用标准库的iostream的话,则不需要其他头文件。
  1. #include "ios.h"
  2. #include <bits/stl_iterator_base_types.h>
  3. #include <bits/stl_iterator_base_funcs.h>
  4. #include <bits/stl_iterator.h>
  5. #include <bits/stl_algobase.h>

  6. template<class ForwardIterator>
  7. void combsort ( ForwardIterator first, ForwardIterator last )
  8. {
  9.     static const double shrink_factor = 1.247330950103979;
  10.     typedef typename std::iterator_traits<ForwardIterator>::difference_type difference_type;
  11.     difference_type gap = std::distance(first, last);
  12.     bool swaps = true;

  13.     while ( (gap > 1) || (swaps == true) ){
  14.         if (gap > 1)
  15.             gap = static_cast<difference_type>(gap/shrink_factor);

  16.         swaps = false;
  17.         ForwardIterator itLeft(first);
  18.         ForwardIterator itRight(first); std::advance(itRight, gap);

  19.         for ( ; itRight!=last; ++itLeft, ++itRight ){
  20.             if ( (*itRight) < (*itLeft) ){
  21.                 std::iter_swap(itLeft, itRight);
  22.                 swaps = true;
  23.             }
  24.         }
  25.     }
  26. }

  27. template<typename T, std::size_t n>
  28. T* end(T (&array)[n])
  29. {
  30.   return array+n;
  31. }

  32. int main() {
  33.     int myints[] = {249, 2423, 232, 21, 1637, 35, 2556, 257};
  34.         combsort(myints, end(myints));
  35.         std::cout << "Sorted list/array: ";
  36.         for(unsigned int i=0; i<8; i++)
  37.                 std::cout << myints[i] << ' ';
  38. }
复制代码

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-13 03:43

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表