Skip to content

Commit 58f327a

Browse files
author
[ravitej]
committed
Stooge sort impelementation using java
1 parent 524a137 commit 58f327a

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

Sorting/StoogeSort/readme.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
#STOOGE SORT
2+
3+
>Input : 2 4 5 3 1
4+
5+
>Output : 1 2 3 4 5
6+
7+
>Explanation:
8+
9+
Initially, swap 2 and 1 following above step 1.
10+
1 4 5 3 2
11+
Now, recursively sort initial 2/3rd of the elements.
12+
1 4 5 3 2
13+
1 3 4 5 2
14+
Then, recursively sort last 2/3rd of the elements.
15+
1 3 4 5 2
16+
1 2 3 4 5
17+
Again, sort the initial 2/3rd of the elements to confirm final data is sorted.
18+
1 2 3 4 5

Sorting/StoogeSort/stooge.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Java program to implement stooge sort
2+
import java.io.*;
3+
4+
public class stooge {
5+
static void stoogesort(int arr[], int l, int h)
6+
{
7+
if (l >= h)
8+
return;
9+
10+
// If first element is smaller than last, swap them
11+
if (arr[l] > arr[h]) {
12+
int t = arr[l];
13+
arr[l] = arr[h];
14+
arr[h] = t;
15+
}
16+
17+
// If there are more than 2 elements in the array
18+
if (h - l + 1 > 2) {
19+
int t = (h - l + 1) / 3;
20+
21+
// Recursively sort first 2/3 elements
22+
stoogesort(arr, l, h - t);
23+
24+
// Recursively sort last 2/3 elements
25+
stoogesort(arr, l + t, h);
26+
27+
// Recursively sort first 2/3 elements again to confirm
28+
stoogesort(arr, l, h - t);
29+
}
30+
}
31+
32+
33+
public static void main(String args[])
34+
{
35+
int arr[] = { 2, 4, 5, 3, 1 };
36+
int n = arr.length;
37+
38+
stoogesort(arr, 0, n - 1);
39+
40+
for (int i = 0; i < n; i++)
41+
System.out.print(arr[i] + " ");
42+
}
43+
}
44+

0 commit comments

Comments
 (0)