关于 GCC 单向旋转算法的一项发现
A discovery about GCC's unidirectional rotation algorithm

原始链接: https://devblogs.microsoft.com/oldnewthing/20260603-00/?p=112378

本摘要旨在探讨 `gcc libstdc++` 中针对随机访问迭代器(random-access iterators)与前向迭代器(forward iterators)所采用的旋转算法。虽然最初预期两者会有所不同,但分析显示,尽管呈现视角不同,这两种算法在功能上是完全一致的。 通过对这两种方法进行旋转采样追踪可以发现,它们执行了相同的交换操作并最终达到相同的状态,只是内部逻辑有所区别。主要差异在于 `libstdc++` 版本具有对称性,如果右侧区块较大,它允许从右向左处理交换;而前向迭代器算法则始终从左向右操作。归根结底,这再次证明了看似不同的技术方案往往共享相同的底层机制。本系列后续将继续分析 `clang` 所使用的循环分解法。

``` Hacker News 最新 | 过往 | 评论 | 提问 | 展示 | 招聘 | 提交 登录 关于 GCC 单向循环移位算法的一个发现 (devblogs.microsoft.com/oldnewthing) 8 分,soheilpro 发布于 1 小时前 | 隐藏 | 过往 | 收藏 | 2 条评论 帮助 srean 4 分钟前 [–] “令人震惊”、“引人注目”、“令人失望”、“会让你震惊”——这篇文章充斥着夸张的修辞。 回复 saagarjha 1 分钟前 | 父节点 [–] 天哪,我真好奇 Raymond 为什么要那样做。 回复 指南 | 常见问题 | 列表 | API | 安全 | 法律 | 申请 YC | 联系 搜索: ```
相关文章

原文

Last time, we looked at the rotation algorithm used by gcc libstdc++ for random-access iterators, and I concluded by noting that we’re going to make a shocking discovery.

As with all shocking discoveries, this one will shock disappoint you.

The discovery is that the gcc libstdc++ algorithm is the same as the forward-iterator algorithm!

Let’s run both algorithms on a problem where the two blocks are A1, A2, A3, B1, B2, B3, B4, B5. I’ll put the old forward iterator algorithm on top and the new gcc libstdc++ algorithm below.

first   mid       last
           
A1 A2 A3 B1 B2 B3 B4 B5
           
first   mid       last

We swap at first and mid, then advance both pointers. The two algorithms agree until first reaches the end of the original A block.

      first   mid   last
           
B1 B2 B3 A1 A2 A3 B4 B5
           
      first   mid   last

The old algorithm recurses in order to exchange A1, A2, A3 with B4, B4. This happens by exchanging A1 with B4 and A2 with B5.

The new algorithm just keeps swapping first with mid, which also exchanges A1 with B4 and A2 with B5.

          first   mid
last
             
B1 B2 B3 B4 B5 A3 A1 A2
             
          first   last
mid

The old algorithm now recurses to swap the A3 block with the A1+A2 block. And that’s what the new algorithm does, too.

So it’s the same algorithm, just with a different point of view. It’s another case of the geeky thrill of discovering that two things are really the same thing, just with different labels.

Now, the two algorithms are not identical. The new algorithm is symmetric and performs its swaps from right to left if the larger block is on the right. The old algorithm always operates from left to right.

But the similarity is striking.

Next time, we’ll look at how clang performs rotation by decomposing into cycles.

联系我们 contact @ memedata.com