From f453b780355abd97b07f8f9f415bc94d3e75987f Mon Sep 17 00:00:00 2001 From: Nathan Fei Date: Thu, 26 Oct 2017 16:51:35 -0400 Subject: [PATCH] Create BogoSort.java --- Sorts/BogoSort.java | 47 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Sorts/BogoSort.java diff --git a/Sorts/BogoSort.java b/Sorts/BogoSort.java new file mode 100644 index 000000000000..4b1d08ab782e --- /dev/null +++ b/Sorts/BogoSort.java @@ -0,0 +1,47 @@ +/* + +an implementation of bogosort +input from command line +to increasing order + +*/ + +import java.util.Random; + +public class BogoSort { + + public static void main(String[] args) { + int[] arr = new int[args.length]; + for (int i = 0; i < args.length; i++) + arr[i] = Integer.parseInt(args[i]); + while(!isSorted(arr)) arr = scramble(arr); + disp(arr); + } + + private static boolean isSorted(int[] arr) { + for (int i = 0; i < arr.length - 1; i++) + if (arr[i + 1] < arr[i]) + return false; + return true; + } + + private static int[] scramble(int[] arr) { + Random rand = new Random(); + int[] scr = new int[arr.length], chk = new int[arr.length]; + int count = 0, index; + while (count < arr.length) { + index = rand.nextInt(arr.length); + if (chk[index] != 1) { + scr[index] = arr[count]; + chk[index] = 1; + count++; + } + } + return scr; + } + + private static void disp(int[] arr) { + for(int i : arr) System.out.print(i + " "); + System.out.println(); + } +} pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy