Write a C program to reverse the elements within a given range in a sorted list. Example : input : 10 9 1 2 4 3 4 6 7 8 10 3 8 output: 1 2 8 7 6 4 4 3 9 10 the sorted list of given array elements is 1 2 3 4 4 6 7 8 9 10 , after reversing the elements with in the range 3 and 8 is 1 2 8 7 6 4 4 3 9 10

 #include <stdio.h>

#include <stdlib.h>


// Function to sort the array

void sortArray(int arr[], int n) {

    for (int i = 0; i < n-1; i++) {

        for (int j = i+1; j < n; j++) {

            if (arr[i] > arr[j]) {

                int temp = arr[i];

                arr[i] = arr[j];

                arr[j] = temp;

            }

        }

    }

}


// Function to reverse elements within a given range

void reverseRange(int arr[], int start, int end) {

    while (start < end) {

        int temp = arr[start];

        arr[start] = arr[end];

        arr[end] = temp;

        start++;

        end--;

    }

}


// Function to print the array

void printArray(int arr[], int size) {

    for (int i = 0; i < size; i++)

        printf("%d ", arr[i]);

    printf("\n");

}


int main() {

    int n, start, end;


    printf("Enter the number of elements: ");

    scanf("%d", &n);


    int *arr = (int *)malloc(n * sizeof(int));

    

    printf("Enter the elements: ");

    for (int i = 0; i < n; i++) {

        scanf("%d", &arr[i]);

    }


    printf("Enter the range (start and end indices): ");

    scanf("%d %d", &start, &end);


    // Sort the array

    sortArray(arr, n);

    printf("Sorted array: ");

    printArray(arr, n);


    // Reverse the elements within the given range

    reverseRange(arr, start, end);


    printf("Array after reversing elements within the range: ");

    printArray(arr, n);


    free(arr);

    return 0;

}


Comments