C++ Array and Vector Operations: Unique Elements & Bubble Sort

Classified in Computers

Written on in English with a size of 5.77 KB

C++ Code Examples: Data Filtering and Sorting

This document presents two fundamental C++ programming examples. The first demonstrates how to process user input to extract and display only unique integer values, effectively removing duplicates. The second illustrates the classic Bubble Sort algorithm for arranging elements in ascending order within a std::vector.

Filtering Duplicate Integers in C++

This C++ program prompts the user to enter 20 integers. It then processes these inputs to identify and store only the unique values, discarding any duplicates. Finally, it displays the list of non-duplicate integers.

Program Description: Unique Element Extraction

  • Initializes an array a of size 20 to store unique elements, along with a subscript to track the current number of unique elements.
  • Iterates 20 times to accept user input.
  • For each input value, it checks against already stored unique elements to determine if it's a duplicate.
  • If the value is not a duplicate, it's added to the a array, and subscript is incremented.
  • Finally, it prints all the unique values collected.

C++ Code for Unique Element Extraction

#include <iostream> // For cin, cout
#include <iomanip>  // For setw

int main() {
    const int SIZE = 20;
    int a[SIZE] = {0}; // Initialize array with zeros
    int subscript = 0; // Tracks the next available position for a unique value
    int duplicate;
    int value;

    std::cout << "Enter 20 integers between 10 and 100:\n";

    // Loop to read 20 integers
    for (int i = 0; i < SIZE; ++i) {
        duplicate = 0; // Assume not a duplicate initially
        std::cin >> value;

        // Check if the entered value is already in the array 'a'
        for (int j = 0; j < subscript; ++j) {
            if (value == a[j]) {
                duplicate = 1; // Mark as duplicate
                break;         // No need to check further
            }
        }

        // If not a duplicate, add it to the array 'a'
        if (!duplicate) {
            a[subscript++] = value;
        }
    }

    std::cout << "\nThe non-duplicate values are:\n";

    // Output the non-duplicate values
    // Loop until a zero is encountered (since array was initialized with zeros)
    // or until the end of the array is reached
    for (int i = 0; a[i] != 0 && i < SIZE; ++i) {
        std::cout << std::setw(4) << a[i];
    }

    std::cout << std::endl;

    return 0;
}

Implementing Bubble Sort in C++

This C++ program demonstrates the Bubble Sort algorithm. It initializes a std::vector with predefined integer values, displays the original order, and then sorts the elements in ascending order using Bubble Sort, finally presenting the sorted list.

Program Description: Bubble Sort Algorithm

  • Defines an array data with initial values and copies them into a std::vector<int> a.
  • Prints the elements of the vector in their original order.
  • Applies the Bubble Sort algorithm using nested loops:
    • The outer loop controls the number of passes.
    • The inner loop compares adjacent elements and swaps them if they are in the wrong order.
  • After sorting, it displays the elements of the vector in ascending order.

C++ Code for Bubble Sort Algorithm

#include <iostream> // For cin, cout
#include <iomanip>  // For setw
#include <vector>   // For std::vector

int main() {
    const int SIZE = 10;
    int data[SIZE] = {2, 6, 4, 8, 10, 12, 89, 68, 45, 37};

    std::vector<int> a; // Declare vector<int> to sort

    // Fill the vector with values from the array
    for (int i = 0; i < SIZE; i++) {
        a.push_back(data[i]);
    }

    int hold; // Temporary location used to swap vector elements

    std::cout << "Data items in original order:\n";

    // Output original vector
    for (int i = 0; i < SIZE; i++) {
        std::cout << std::setw(4) << a[i];
    }
    std::cout << std::endl; // Added newline for better formatting

    // Bubble Sort Algorithm
    // Loop to control number of passes
    for (int pass = 0; pass < SIZE - 1; pass++) {
        // Loop to control number of comparisons per pass
        // In each pass, the largest unsorted element "bubbles" to its correct position
        for (int j = 0; j < SIZE - 1 - pass; j++) {
            // Compare side-by-side elements and swap them if
            // the first element is greater than the second element
            if (a[j] > a[j + 1]) {
                hold = a[j];
                a[j] = a[j + 1];
                a[j + 1] = hold;
            }
        }
    }

    std::cout << "\nData items in ascending order:\n";

    // Output sorted vector
    for (int k = 0; k < SIZE; k++) {
        std::cout << std::setw(4) << a[k];
    }

    std::cout << std::endl;

    return 0;
}

Key Takeaways

These examples demonstrate fundamental C++ concepts for data manipulation:

  • Array and Vector Usage: Practical application of static arrays and dynamic std::vector for data storage.
  • Input/Output Operations: Effective use of std::cin for input and std::cout with std::setw for formatted output.
  • Algorithmic Thinking: Implementation of basic algorithms for data processing (duplicate removal) and sorting (Bubble Sort).
  • Control Structures: Utilization of for loops and if statements for program flow control.

Related entries: