Gnome sort: Sorting by Exchanging

来源:互联网 发布:网络女主播喝醉 编辑:程序博客网 时间:2024/05/24 04:07

Gnome sort:地精排序


Animation

gnome sort
Visualisation of Gnome sort


Complexity

Class Sorting algorithm Data structure Array 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:5032:873:5124:615:9086:1707:8978:2759:65310:42611:15412:50913:61214:67715:76516:703Sorted Ks:1:612:873:1544:1705:2756:4267:5038:5099:51210:61211:65312:67713:70314:76515:89716:908

Reference

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

0 0
原创粉丝点击