2021-05-27gnomesort 地精排序、傻瓜排序、矮子排序

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.csdn.net/winark/article/details/5918944

https://www.cnblogs.com/kkun/archive/2011/11/23/gnome_sort.html

猜你喜欢

转载自blog.csdn.net/weiabc/article/details/117338541