Sorting Elements in an Array in C++

 


Sorting an array means arranging the elements in a specific order, usually either ascending (smallest to largest) or descending (largest to smallest). C++ provides several ways to sort arrays, with the most common approach being to use the sort() function from the <algorithm> library.


Example: Sorting an Array in Ascending Order

Using the sort() Function from <algorithm>:

The sort() function can be used to sort elements in ascending or descending order.

Sorting in Ascending Order (Default):

#include <iostream>
#include <algorithm>  // For sort
using namespace std;

int main() {
    int arr[] = {50, 10, 40, 20, 30};
    int size = sizeof(arr) / sizeof(arr[0]);  // Calculate the number of elements

    // Sort the array in ascending order (default behavior of sort())
    sort(arr, arr + size);

    // Output the sorted array
    cout << "Array after sorting in ascending order: ";
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;

    return 0;
}

Explanation:

  1. The sort() function takes two arguments: the beginning of the array (arr) and the end of the array (arr + size).
  2. By default, sort() arranges the elements in ascending order.

Output:

Array after sorting in ascending order: 10 20 30 40 50

Example: Sorting in Descending Order

To sort the array in descending order, you can provide a custom comparator to the sort() function. This is done using the greater<int>() function from the <functional> library.

#include <iostream>
#include <algorithm>  // For sort
#include <functional> // For greater
using namespace std;

int main() {
    int arr[] = {50, 10, 40, 20, 30};
    int size = sizeof(arr) / sizeof(arr[0]);  // Calculate the number of elements

    // Sort the array in descending order
    sort(arr, arr + size, greater<int>());

    // Output the sorted array
    cout << "Array after sorting in descending order: ";
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;

    return 0;
}

Explanation:

  1. The greater<int>() function is used as a comparator to tell sort() to arrange the array in descending order.
  2. The greater<int>() comparator returns true when the first element is greater than the second element, ensuring the elements are sorted in descending order.

Output:

Array after sorting in descending order: 50 40 30 20 10

Manual Sorting (Bubble Sort)

If you want to implement your own sorting algorithm, you can use Bubble Sort, which is a simple sorting algorithm. It repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.

Bubble Sort Example:

#include <iostream>
using namespace std;

void bubbleSort(int arr[], int size) {
    for (int i = 0; i < size - 1; i++) {
        for (int j = 0; j < size - i - 1; j++) {
            // Swap if the element found is greater than the next element
            if (arr[j] > arr[j + 1]) {
                swap(arr[j], arr[j + 1]);
            }
        }
    }
}

int main() {
    int arr[] = {50, 10, 40, 20, 30};
    int size = sizeof(arr) / sizeof(arr[0]);  // Calculate the number of elements

    // Call bubbleSort to sort the array in ascending order
    bubbleSort(arr, size);

    // Output the sorted array
    cout << "Array after sorting using Bubble Sort: ";
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;

    return 0;
}

Explanation:

  1. The bubbleSort() function compares each pair of adjacent elements.
  2. If an element is greater than the next one, they are swapped.
  3. The process is repeated for each element until the array is sorted.

Output:

Array after sorting using Bubble Sort: 10 20 30 40 50

Key Points:

  • The sort() function from the C++ Standard Library is the most efficient and easiest way to sort an array.
  • Bubble Sort is a simple but inefficient algorithm with a time complexity of O(n²), and it's typically used for educational purposes.
  • Sorting in ascending order is the default behavior of sort(), but you can use the greater<int>() comparator to sort in descending order.

Would you like to explore other sorting algorithms, like Selection Sort or Insertion Sort?

Post a Comment

0 Comments