Topic-33:Sorting in Array

Sorting an array involves arranging its elements in a specific order, such as ascending or descending order. One of the most commonly used sorting algorithms is the bubble sort algorithm.

Example:

#include <stdio.h>

 

#define MAX_SIZE 100

 

void bubbleSort(int array[], int size) {

    // Outer loop for passes

    for (int i = 0; i < size – 1; i++) {

        // Inner loop for comparisons and swapping

        for (int j = 0; j < size – i – 1; j++) {

            // Compare adjacent elements

            if (array[j] > array[j + 1]) {

                // Swap them if they are in the wrong order

                int temp = array[j];

                array[j] = array[j + 1];

                array[j + 1] = temp;

            }

        }

    }

}

 

int main() {

    int arr[MAX_SIZE]; // Array to be sorted

    int size;

 

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

    scanf(“%d”, &size);

 

    printf(“Enter %d elements:\n”, size);

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

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

    }

 

    // Call the bubbleSort function to sort the array

    bubbleSort(arr, size);

 

    // Print the sorted array

    printf(“Sorted array:\n”);

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

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

    }

    printf(“\n”);

 

    return 0;

}

 

Explanation:

  • We have a function bubbleSort that takes the array and its size as parameters.
  • Inside bubbleSort, we use two nested loops. The outer loop iterates through the array for passes, and the inner loop iterates through the array for comparisons and swapping.
  • In each pass, we compare adjacent elements and swap them if they are in the wrong order (in ascending order, the smaller element should come before the larger one).
  • After completing all passes, the array will be sorted in ascending order.
  • In the main function, we take input from the user for the number of elements and the elements themselves.
  • We then call the bubbleSort function to sort the array.
  • Finally, we print the sorted array.
Bubble sort is not the most efficient sorting algorithm, especially for large datasets, but it’s relatively simple to understand and implement. There are other more efficient sorting algorithms such as quicksort, mergesort, and heapsort, which are often preferred for larger datasets.

Leave a Comment

Your email address will not be published. Required fields are marked *