如何对间隔固定(索引呈等差数列)的元素进行排序?
如何对间隔固定(索引呈等差数列)的元素进行排序?
嘿,这个需求挺实用的!我看你已经写了个不错的开头,咱们把它补全,再聊聊这个实现的思路~
先再明确下你的需求:比如有一个数组11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,你想对索引为1、4、7、10(也就是从起始位置start开始,每次跳jump步,索引呈等差数列)的元素排序,排序后这些位置的元素变成1、4、7、10,最终数组变成11, 1, 9, 8, 4, 6, 5, 7, 3, 2, 10, 0对吧?
你已经完成了核心的两步:提取目标元素、对提取的元素排序,就差最后把排好的元素放回原数组对应位置了!下面是补全后的完整可运行代码:
#include <iostream> #include <vector> #include <algorithm> void sort_constant_jump(std::vector<int> &foo, int start, int jump) { std::vector<int> need_to_sort; // 第一步:提取需要排序的目标元素 for(int index = start; index < foo.size(); index += jump) { need_to_sort.push_back(foo[index]); } // 第二步:用标准库排序,省心又高效 std::sort(need_to_sort.begin(), need_to_sort.end()); // 第三步:把排好序的元素放回原数组对应位置 int sort_idx = 0; for(int index = start; index < foo.size(); index += jump) { foo[index] = need_to_sort[sort_idx++]; } } int main() { std::vector<int> arr = {11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; // 调用函数:起始索引1,每次跳3步 sort_constant_jump(arr, 1, 3); // 打印验证结果 for(int num : arr) { std::cout << num << " "; } std::cout << std::endl; // 输出:11 1 9 8 4 6 5 7 3 2 10 0 return 0; }
这个实现的优点:
- 代码简单直观,可读性拉满,谁看了都知道你在干嘛
- 复用了标准库的
std::sort,不用自己造排序的轮子,效率和稳定性都有保障 - 逻辑清晰,分三步完成,排查问题也方便
如果你的数组特别大,不想用额外的临时数组占内存,也可以实现一个自定义迭代器来直接在原数组上排序,但这种写法复杂度会高不少,日常开发里,上面的临时数组方案已经完全够用啦~
备注:内容来源于stack exchange,提问作者justANewb stands with Ukraine
相关产品推荐
相关产品推荐

