Home »
C/C++ Data Structure Programs
C program to implement Stooge sort algorithm
In this tutorial, we will learn how to implement Stooge sort algorithm using C program?
By Nidhi Last updated : August 06, 2023
Problem statement
Here, we will create an array of integers then we will read array elements from the user and implement the Stooge sort algorithm to arrange array elements in ascending order.
C program to implement Stooge sort algorithm
The source code to implement the Stooge sort algorithm is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.
// C program to implement Stooge sort algorithm
#include <stdio.h>
#define MAX 5
void StoogeSort(int arr[], int i, int j)
{
int temp = 0;
int temp1 = 0;
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
if ((i + 1) >= j)
return;
temp1 = (int)((j - i + 1) / 3);
StoogeSort(arr, i, j - temp1);
StoogeSort(arr, i + temp1, j);
StoogeSort(arr, i, j - temp1);
}
int main()
{
int i = 0;
int arr[MAX];
printf("Enter array elements:\n");
while (i < MAX) {
printf("Element[%d]: ", i);
scanf("%d", &arr[i]);
i++;
}
StoogeSort(arr, 0, MAX - 1);
printf("Sorted Array: \n");
i = 0;
while (i < MAX) {
printf("%d ", arr[i]);
i++;
}
printf("\n");
return 0;
}
Output
RUN 1:
Enter array elements:
Element[0]: 43
Element[1]: 23
Element[2]: 76
Element[3]: 45
Element[4]: 65
Sorted Array:
23 43 45 65 76
RUN 2:
Enter array elements:
Element[0]: 10
Element[1]: 15
Element[2]: 5
Element[3]: 40
Element[4]: 30
Sorted Array:
5 10 15 30 40
Explanation
Here, we created two functions StoogeSort() and main(). The StoogeSort() function is a recursive function, which is used to sort array elements in ascending order.
In the main() function, we read array elements from the user. Then we sorted the elements of the array in ascending order using the StoogeSort() function and print the sorted array on the console screen.