Skip to content

Commit ee5136c

Browse files
Merge pull request TheAlgorithms#158 from karimElmougi/BogoSort
Bogo sort
2 parents 60275e9 + 5919171 commit ee5136c

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

Sorts/BogoSort.java

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package Sorts;
2+
3+
import java.util.Random;
4+
5+
public class BogoSort {
6+
private static <T> void swap(T array[], int first, int second){
7+
T randomElement = array[first];
8+
array[first] = array[second];
9+
array[second] = randomElement;
10+
}
11+
12+
private static <T extends Comparable<T>> boolean isSorted(T array[]){
13+
for(int i = 0; i<array.length-1; i++){
14+
if(array[i].compareTo(array[i+1]) > 0) return false;
15+
}
16+
return true;
17+
}
18+
19+
// Randomly shuffles the array
20+
private static <T> void nextPermutation(T array[]){
21+
int length = array.length;
22+
Random random = new Random();
23+
24+
for (int i = 0; i < array.length; i++) {
25+
int randomIndex = i + random.nextInt(length - i);
26+
swap(array, randomIndex, i);
27+
}
28+
}
29+
30+
public static <T extends Comparable<T>> void bogoSort(T array[]) {
31+
while(!isSorted(array)){
32+
nextPermutation(array);
33+
}
34+
}
35+
36+
// Driver Program
37+
public static void main(String[] args)
38+
{
39+
// Integer Input
40+
int[] arr1 = {4,23,6,78,1,54,231,9,12};
41+
int last = arr1.length;
42+
Integer[] array = new Integer[last];
43+
for (int i=0;i<last;i++) {
44+
array[i] = arr1[i];
45+
}
46+
47+
bogoSort(array);
48+
49+
// Output => 1 4 6 9 12 23 54 78 231
50+
for(int i=0; i<last; i++)
51+
{
52+
System.out.print(array[i]+"\t");
53+
}
54+
System.out.println();
55+
56+
// String Input
57+
String[] array1 = {"c", "a", "e", "b","d"};
58+
last = array1.length;
59+
60+
bogoSort(array1);
61+
62+
//Output => a b c d e
63+
for(int i=0; i<last; i++)
64+
{
65+
System.out.print(array1[i]+"\t");
66+
}
67+
}
68+
}

0 commit comments

Comments
 (0)
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