Gnome sort: Sorting by Exchanging

Gnome sort:地精排序


Animation

gnome sort
Visualisation of Gnome sort


Complexity

ClassSorting algorithm
Data structureArray
Worst case performance O(n2)
Best case performance Ω(n)
Average case performance O(n2)
Worst case space complexity O(1) auxiliary

Java program

/**
 * User: >_<
 * Date: 11/12/15
 * Time: 10:41 AM
 */

public class GnomeSort {

    public static void gnome_sort(int[] input){
        int pos = 1;
        while (pos < input.length){
            if(input[pos] >= input[pos-1])
                pos++;
            else{
                int temp = input[pos];
                input[pos] = input[pos-1];
                input[pos-1] = temp;
                if(pos > 1)
                    pos--;
            }
        }

    }

    public static void main(String[] args) {

        //Prepare the data
        int[] number = {503,87,512,61,908,170,897,275,653,426,154,509,612,677,765,703};

        //Output unsorted Keys
        System.out.println("Unsorted Ks:");
        for(int i=1; i<=number.length; i++){
            System.out.println(i+":"+number[i-1]);
        }
        System.out.println();

        //Kernel of the Algorithm!
        gnome_sort(number);

        //Output sorted Keys
        System.out.println("Sorted Ks:");
        for(int i=1; i<=number.length; i++){
            System.out.println(i+":"+number[i-1]);
        }
    }
}


Outputs

Unsorted Ks:
1:503
2:87
3:512
4:61
5:908
6:170
7:897
8:275
9:653
10:426
11:154
12:509
13:612
14:677
15:765
16:703

Sorted Ks:
1:61
2:87
3:154
4:170
5:275
6:426
7:503
8:509
9:512
10:612
11:653
12:677
13:703
14:765
15:897
16:908

Reference

https://en.wikipedia.org/wiki/Gnome_sort

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值