C program to sort an array


Submit solution

Points: 10 (partial)
Time limit: 8.0s
Memory limit: 38M

Author:
Problem type
Allowed languages
C

Problem Statement

WAP to sort an array a.Ascending order b.Descending order

Sample Input

8 3 2 6 5

Sample Output

2 3 5 6 8

8 6 5 3 2


Comments


  • 1
    kirthik_saran  commented on May 14, 2023, 12:44 p.m.

    include <stdio.h>

    int main() { int n, i, j, temp;

    // Read array size and elements
    //printf("Enter the size of the array: ");
    scanf("%d", &n);
    int a[n];
    //printf("Enter %d elements: ", n);
    for (i = 0; i < n; i++) {
        scanf("%d", &a[i]);
    }
    
    // Sort in ascending order
    for (i = 0; i < n - 1; i++) {
        for (j = i + 1; j < n; j++) {
            if (a[i] > a[j]) {
                temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
    }
    
    // Print sorted array in ascending order
    //printf("Sorted array in ascending order: ");
    for (i = 0; i < n; i++) {
        printf("%d ", a[i]);
    }
    printf("\n");
    
    // Sort in descending order
    for (i = 0; i < n - 1; i++) {
        for (j = i + 1; j < n; j++) {
            if (a[i] < a[j]) {
                temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
    }
    
    // Print sorted array in descending order
    //printf("Sorted array in descending order: ");
    for (i = 0; i < n; i++) {
        printf("%d ", a[i]);
    }
    printf("\n");
    
    return 0;

    }