list = [1, 4, 6, 5, 2, 3]
def gnomesort(seq):
i = 0
while i < len(seq): # 进入一个循环
if i == 0 or seq[i - 1] <= seq[i]: #如果站在第一个元素 或 前一个元素小于当前元素 i++
i += 1
else: #否则
seq[i], seq[i - 1] = seq[i - 1], seq[i] #交换两元素 往回站一位 i++
i -= 1 #实际python 是没有i++,i--的
gnomesort(list)
print(list)
QTC++版:
#include <stdio.h>//printf()
#include <stdlib.h>//system()
int main()
{
int array[6]={1,4,6,5,2,3};
int i=0;
while (i<6) {
if(i==0 || array[i-1]<array[i])
i++;
else{
array[i-1]^=array[i];
array[i]^=array[i-1];
array[i-1]^=array[i];
i--;
}
}
for(int i = 0; i<6; i++)
{
printf("%d ",array[i]);
}
system("pause");
return 0;
}
运行结果:
[1, 2, 3, 4, 5, 6]
它的优化及C++版见:
https://blog.youkuaiyun.com/winark/article/details/5918944
https://www.cnblogs.com/kkun/archive/2011/11/23/gnome_sort.html
本文介绍了gnome_sort算法的Python实现,并给出了C++版本的代码,展示了如何对序列进行排序。通过交换元素实现排序,最终得到升序排列的序列[1, 2, 3, 4, 5, 6]。文章还提供了相关资源链接以供深入学习。
1173

被折叠的 条评论
为什么被折叠?



