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

Popular posts from this blog

Write a c program to Create a Circular Linked list and perform Following Operations A. Insertion At Beginning B. Insertion At End C. Insertion After a particular node Insertion Before a particular node E. Insertion at specific position F. Search a particular node G. Return a particular node H. Deletion at the beginning I. Deletion at the end J. Deletion after a particular node K. Deletion before a particular node L. Delete a particular node M. Deletion at a specific position

Write a c program to check whether the created linked list is palindrome or not

Write a c program to Create a Circular single Linked list and perform Following Operations A. Insertion After a particular node B. Insertion Before a particular node C. Search a particular node D. Return a particular node E. Deletion before a particular node F. Delete a particular node