Bogosort: Sorting by Exchanging

来源:互联网 发布:linux的uniq 编辑:程序博客网 时间:2024/06/10 15:59

Bogosort


Animation

single shuffle bogosort
A possible, but improbable, single shuffle execution of the bogo sort algorithm.


Complexity

Class Sorting algorithm Data structure Array Worst case performance Unbounded Best case performance θ(n) Average case performance O((n+1)!) Worst case space complexity O(n)

Java program

import java.util.Random;/** * User: >_< * Date: 11/12/15 * Time: 12:23 PM */public class BogoSort {    public static void shuffle(int[] input, int size){        int i, r, t;        Random random = new Random();        for(i=0; i<size-1; i++){            r = random.nextInt(10000) % (size-i);            t = input[i];            input[i] = input[r+i];            input[r+i] = t;        }        //Output shuffled Keys        System.out.println("Shuffled Ks:");        for(int j=1; j<=input.length; j++){            System.out.println(j+":"+input[j-1]);        }        System.out.println();    }    public static void bogo_sort(int[] input, int size){        int i;        int flag;        while (true){            flag = 0;            for(i=0; i<size-1; i++){                if(input[i] > input[i+1]){                    flag = 1;                    break;                }            }            if(flag == 0)                break;            shuffle(input, size);        }    }    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!        bogo_sort(number, number.length);        //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:703Shuffled Ks:1:7652:8973:4264:2755:6126:5127:6538:879:15410:67711:90812:50313:50914:6115:17016:703Shuffled Ks:1:7652:2753:874:7035:6126:1547:618:6779:90810:51211:42612:50313:65314:17015:50916:897Shuffled Ks:1:6532:873:1704:7035:6126:6777:8978:4269:50310:90811:50912:76513:51214:6115:27516:154......

Reference

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

0 0