Add

C program to implement Stooge sort algorithm

 


// 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:

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.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.