- Notifications
You must be signed in to change notification settings - Fork 363
Expand file tree
/
Copy pathStoogeSort.java
More file actions
Latest commit
43 lines (43 loc) · 1.48 KB
/
Copy pathStoogeSort.java
File metadata and controls
43 lines (43 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
importjava.util.Arrays;
publicclassStoogeSort {
// Function to swap two elements
publicstaticvoidswap(int[] arr, inti, intj) {
inttemp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// Stooge Sort function
publicstaticvoidstoogeSort(int[] arr, intlow, inthigh) {
if (low >= high)
return;
// If the first element is greater than the last element, swap them
if (arr[low] > arr[high])
swap(arr, low, high);
// If there are more than 2 elements in the array
if (high - low + 1 > 2) {
intt = (high - low + 1) / 3;
// Sort the first two-thirds of the array
stoogeSort(arr, low, high - t);
// Sort the last two-thirds of the array
stoogeSort(arr, low + t, high);
// Sort the first two-thirds of the array again
stoogeSort(arr, low, high - t);
}
}
// Function to print the array
publicstaticvoidprintArray(int[] arr) {
for (inti = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
// Driver Code
publicstaticvoidmain(String[] args) {
int[] arr = { 10, 5, 8, 2, 1, 6 };
System.out.print("Original array: ");
printArray(arr);
stoogeSort(arr, 0, arr.length - 1);
System.out.print("Sorted array: ");
printArray(arr);
}
}