C++ Coding Test Course, Bubble Sort Program 2

Hello! In this tutorial, we will learn how to implement the Bubble Sort algorithm using C++. Bubble Sort is a simple and easy-to-understand sorting algorithm, mainly used for educational purposes. In this article, we will explain the basic concepts of Bubble Sort, its time complexity, and the actual implementation step by step.

Overview of Bubble Sort Algorithm

Bubble Sort is a method that sorts by comparing two adjacent elements. This process is repeated until all elements of the list are sorted. The name Bubble Sort comes from the way the largest value ‘bubbles’ up to the back.

How Bubble Sort Works

  1. Compare the first element of the list with the second element.
  2. If the first element is greater than the second element, swap their positions.
  3. Repeat this process all the way to the end of the list. One cycle of this process is called a ‘pass’.
  4. Repeat steps 1 to 3 until the sorting is complete.

Time Complexity

The time complexity of Bubble Sort is O(n^2) in the worst case. This is because each element of the list needs to be compared once. The best case (when already sorted) is also O(n). For this reason, Bubble Sort is inefficient for sorting large datasets.

Algorithm Implementation

Now, let’s implement Bubble Sort through C++ code. First, we’ll take a look at the basic Bubble Sort code and explain each part.

#include <iostream>
using namespace std;

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

// Array printing function
void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

// Main function
int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr) / sizeof(arr[0]);
    
    cout << "Array before sorting: ";
    printArray(arr, n);
    
    bubbleSort(arr, n);
    
    cout << "Array after sorting: ";
    printArray(arr, n);
    return 0;
}

Code Explanation

  • #include <iostream>: This is the header file for standard input and output.
  • swap(arr[j], arr[j + 1]): This uses C++’s built-in function swap to exchange the current element with the next one.
  • printArray function: This is a function to print the given array.
  • main function: This is the starting point of the program, where array initialization and sorting calls take place.

Execution Result

Running the above code produces the following results:

Array before sorting: 64 34 25 12 22 11 90 
Array after sorting: 11 12 22 25 34 64 90 

By comparing the array before and after sorting, we can confirm that Bubble Sort is functioning correctly.

Ways to Improve Bubble Sort

The basic Bubble Sort implementation includes unnecessary comparisons. If no swaps occur during a pass, it indicates that the list is already sorted, and no additional passes are needed. This can enhance the efficiency of the algorithm.

void improvedBubbleSort(int arr[], int n) {
    bool swapped;
    for (int i = 0; i < n - 1; i++) {
        swapped = false;
        for (int j = 0; j < n - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                swap(arr[j], arr[j + 1]);
                swapped = true; // Record that a swap occurred
            }
        }
        if (!swapped) break; // Exit loop if no more swaps
    }
}

Conclusion

In this tutorial, we learned how to implement Bubble Sort using C++. Although it is a simple algorithm, it is less efficient in practice, requiring more efficient algorithms. However, Bubble Sort is worth mentioning due to its educational value.

We will continue to provide C++ algorithm tutorials, so please stay tuned! If you have any questions or comments, please leave them in the comments!

C++ Coding Test Course, Bubble Sort Program 1

In this course, we will cover how to implement the Bubble Sort algorithm using C++. Bubble Sort is one of the simplest sorting algorithms, which sorts by comparing two adjacent elements and moving the larger element backward. This algorithm will help you understand the basics of sorting algorithms and learn how to implement it in C++.

Problem Definition

Write a program to sort a given integer array in ascending order.

Input

The input is an array consisting of multiple integers. For example, let's assume the following array is given:
[64, 34, 25, 12, 22, 11, 90]

Output

Output the result of the array sorted in ascending order. For example, the output for the above input would be:
[11, 12, 22, 25, 34, 64, 90]

Bubble Sort Algorithm

The basic idea of Bubble Sort is to compare two adjacent elements to sort them. If the first element is larger than the second element, the two elements are swapped. This process is repeated until the end of the array, and at the end of each iteration, the largest element moves to the last position. Below are simple steps to explain the Bubble Sort algorithm:

  1. Start from the first element of the array and compare two adjacent elements.
  2. If the first element is larger than the second element, swap the two elements.
  3. Repeat this process until the end of the array.
  4. Repeat this process for the length of the array – 1, so that if a sorted section is created, you can terminate the loop early.

C++ Code Implementation

Now, let’s implement Bubble Sort using C++. Below is the C++ code that implements Bubble Sort:

 
#include <iostream>
#include <vector>

using namespace std;

void bubbleSort(vector<int>& arr) {
    int n = arr.size();
    bool swapped;
    
    // Iterate through all elements of the array
    for (int i = 0; i < n - 1; i++) {
        swapped = false;
        // The last i elements are already sorted, so iterate until n-i-1
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                // Swap the two elements
                swap(arr[j], arr[j + 1]);
                swapped = true;
            }
        }
        // If no elements were swapped, the array is already sorted, so we exit
        if (!swapped) break;
    }
}

int main() {
    vector<int> data = {64, 34, 25, 12, 22, 11, 90};
    
    cout << "Array before sorting: ";
    for (int num : data) {
        cout << num << " ";
    }
    
    bubbleSort(data);
    
    cout << "\nArray after sorting: ";
    for (int num : data) {
        cout << num << " ";
    }
    
    return 0;
}

Code Explanation

The above code is a simple example of how to implement Bubble Sort in C++. First, we declare and initialize an integer array using the vector library. The bubbleSort function performs the sorting operation on the passed array.

  • int n = arr.size(); – Gets the size of the array.
  • for (int i = 0; i < n - 1; i++) – Iterates through all elements of the array.
  • for (int j = 0; j < n - i - 1; j++) – Compares within the range of the last i sorted elements.
  • if (arr[j] > arr[j + 1]) – If the two elements are not in order, uses the swap function to exchange them.
  • if (!swapped) break; – If no swaps occurred, the array is already sorted, so it exits the loop early.

Testing and Result Verification

Now, let’s execute the code to check the results. The output when the above code is executed is as follows:


Array before sorting: 64 34 25 12 22 11 90 
Array after sorting: 11 12 22 25 34 64 90 

Algorithm Analysis

Bubble Sort is easy to understand, but it has issues with efficiency. The time complexity in the worst and average cases is O(n²). This means that performance significantly degrades as the size of the array increases. For this reason, Bubble Sort is more suitable for educational purposes than for practical applications.

Time Complexity

  • Worst case: O(n²)
  • Average case: O(n²)
  • Best case: O(n) (when already sorted)

Space Complexity

  • O(1) (as it directly modifies the given array)

Pros and Cons of Bubble Sort

Pros

  • The algorithm is simple.
  • It is easy for beginners to understand.
  • It can identify whether it is already sorted on its own.

Cons

  • High time complexity makes it inefficient for real applications.
  • Not recommended for large datasets.

Conclusion

In this course, we learned how to implement sorting algorithms in C++ through Bubble Sort. We gained an understanding of the basic concepts of Bubble Sort and its algorithm implementation. In the future, I encourage you to study more efficient sorting algorithms (e.g., Quick Sort, Merge Sort, etc.) in depth.

I hope this article was helpful for your C++ coding test preparation. If you have any further questions or would like to learn about more algorithms, please leave a comment!

C++ Coding Test Course, Finding the Kth Number in an Array

Today, we will learn about one of the frequently asked problems in C++ coding tests, “Finding the Kth Smallest Number in an Array.” The goal of this problem is to find the Kth smallest number in a sorted array. We will analyze how to solve this problem step by step through an example.

Problem Description

Write a program to find the Kth smallest number in the given array. Assume that the elements of the array are distinct integers ranging from 1 to N.

Input

  • The first line contains the size of the array N and K. (1 ≤ N ≤ 100,000, 1 ≤ K ≤ N)
  • The second line contains N integers.

Output

Output the Kth smallest number.

Example

Input Example:

5 2
9 3 1 5 2

Output Example:

2

Problem Solving Strategy

The necessary steps to solve this problem are as follows:

  1. Sort the given array.
  2. Find the K-1 (indexing from 0) element.
  3. Print that value.

C++ Code Implementation

Now, let’s implement the C++ code to solve the given problem. To sort an array in C++, we can use the std::sort function. Below is the code applying that algorithm:

#include 
#include 
#include 

int main() {
    int N, K;
    std::cin >> N >> K; // Input N and K
    std::vector arr(N); // Create an array of size N

    for (int i = 0; i < N; ++i) {
        std::cin >> arr[i]; // Input array elements
    }

    std::sort(arr.begin(), arr.end()); // Sort the array

    std::cout << arr[K - 1] << std::endl; // Output the Kth number (0-indexed)
    return 0;
}

Code Explanation

The above code operates in the following manner:

  1. First, include the iostream, vector, and algorithm libraries. The former is needed for input and output, while the latter is needed for sorting the array.
  2. Declare variables N and K and receive input from the user.
  3. Create an integer vector arr of size N and input the array elements from the user.
  4. Sort the vector using the std::sort function.
  5. Output the Kth smallest number. Since array indexing starts from 0, K - 1 is used.

Complexity Analysis

The time complexity of this algorithm mainly arises from the sorting process. C++’s std::sort has an average time complexity of O(N log N), so the overall time complexity of the algorithm is O(N log N). The space complexity requires O(N) to store the input array.

Additional Problems

You can modify such problems to solve various difficulties. For example:

  • When duplicate elements are present
  • Finding the Kth largest number
  • Finding the Kth number in a subarray

Remember that by slightly modifying the logic for each case, you can easily adapt to them.

Conclusion

In this post, we learned how to find the Kth number in an array. Through the problem-solving process and C++ implementation, we could learn about basic sorting algorithms and how to handle arrays. I encourage you to practice various variant problems. I hope this helps you prepare for your coding tests!

C++ Coding Test Course, Arrays and Lists

Coding tests are an important tool used by many companies today to evaluate job seekers. Today, we will discuss a problem centered around arrays and lists. Arrays and lists are the most basic forms of data structures and are fundamentally used in many algorithm problems. An array stores data in a fixed size of contiguous memory space, while a list can store elements in a dynamic size. Understanding the differences between these two and developing problem-solving skills using them is important.

Problem: Find the Sum of Two Numbers in an Array

Find the indices of two numbers in the given integer array that can make a specific sum. The elements of the array can be duplicated, and the two numbers must be selected from different indices.

Input Format

  • The first line contains the size of the array n (1 ≤ n ≤ 10^4).
  • The second line contains n integers of the array a[0], a[1], ..., a[n-1] (1 ≤ a[i] ≤ 10^9).
  • The third line contains the integer target that needs to be found.

Output Format

Output the indices of the two found numbers, separated by a space. If they do not exist, output -1.

Example

    Input:
    5
    2 7 11 15
    9

    Output:
    0 1
    

Problem-Solving Strategy

This problem is a classic example of finding the sum of two numbers in an array and can be solved through the following process:

  1. Using a HashMap:
  2. Use a HashMap to store the array elements and their indices. For each element, calculate target - current_number and check if that value is present in the HashMap. If it exists, return that index and the current index. This approach has an average time complexity of O(n).

C++ Code Implementation


#include <iostream>
#include <unordered_map>
#include <vector>

using namespace std;

vector twoSum(vector& nums, int target) {
    unordered_map hashMap; // Declaring HashMap
    for (int i = 0; i < nums.size(); ++i) {
        int complement = target - nums[i]; // Finding needed number
        if (hashMap.find(complement) != hashMap.end()) {
            return {hashMap[complement], i}; // Returning indices
        }
        hashMap[nums[i]] = i; // Storing number and its index
    }
    return {-1}; // If not found
}

int main() {
    int n, target;
    cin >> n;
    vector nums(n);
    for (int i = 0; i < n; ++i) {
        cin >> nums[i]; // Input array
    }
    cin >> target; // Input target

    vector result = twoSum(nums, target);
    for (int idx : result) {
        cout << idx << " "; // Output result
    }
    return 0;
}

Code Explanation

The above code works by taking the given array and target value as input and finding the indices of two numbers. By using unordered_map to store each number and its index, it can be solved while traversing the array only once. This ensures a time complexity of O(n) even in the worst case.

Result Verification

To verify that the written code works correctly, we will prepare various test cases. For example:

  • n=5, input array: [2, 7, 11, 15], target: 9 → result: 0 1
  • n=4, input array: [3, 2, 4], target: 6 → result: 1 2
  • n=3, input array: [3, 3], target: 6 → result: 0 1
  • n=2, input array: [1, 2], target: 3 → result: 0 1
  • n=1, input array: [2], target: 2 → result: -1 (no element exists)

Conclusion

Today, we covered a coding test problem using arrays and lists. The problem of finding the sum of two numbers is not a difficult one, but it is worth practicing given the various approaches available. Using HashMaps is a good example of efficiently reducing time complexity. In the next lesson, we will cover other data structures or algorithm approaches. Keep practicing coding!

C++ Coding Test Course, Exploring Mazes

Problem Description

This is a problem of exploring a given maze to find a path to the exit. The maze is given as a 2D array,
where 0 represents a walkable path, and 1 represents a wall. The starting point is (0, 0) and the exit is (n-1, m-1).
The size of the maze is n x m, and you need to implement an algorithm to explore the maze.

Input Format

The first line contains the size of the maze n and m. (1 ≤ n, m ≤ 100)
The next n lines will provide the information of the maze consisting of 0s and 1s.

Output Format

If it is possible to reach the exit, print the length of that path; if it is impossible, print -1.

Example Input

    5 5
    0 1 0 0 0
    0 1 0 1 0
    0 0 0 1 0
    1 1 0 1 0
    0 0 0 0 0
    

Example Output

    9
    

Problem Solving Approach

This problem can be explored using BFS (Breadth-First Search) or DFS (Depth-First Search).
Since the first discovered path in BFS is the shortest path, it is recommended to use BFS for grid exploration.

If using BFS, you can explore the nodes that can be moved to from the current position using a queue,
check for visit status, and then add the new position to the queue.
This method allows you to find the shortest path to the exit.

C++ Code Implementation

Below is the C++ code to solve the maze exploration problem.


#include <iostream>
#include <vector>
#include <queue>
#include <utility>

using namespace std;

// Directions: Up, Down, Left, Right
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};

int bfs(const vector>& maze, int n, int m) {
    queue> q; // Queue declaration
    q.push({0, 0}); // Starting position (0, 0)
    
    vector> distance(n, vector(m, -1)); // Distance array
    distance[0][0] = 1; // Initialize the distance for the starting point to 1

    while (!q.empty()) {
        auto current = q.front(); q.pop();
        int x = current.first;
        int y = current.second;

        // If the target point is reached
        if (x == n - 1 && y == m - 1) {
            return distance[x][y]; // Return the path length
        }

        // Explore adjacent nodes
        for (int i = 0; i < 4; i++) {
            int nx = x + dx[i];
            int ny = y + dy[i];

            // Check bounds and if movement is possible
            if (nx >= 0 && nx < n && ny >= 0 && ny < m && 
                maze[nx][ny] == 0 && distance[nx][ny] == -1) {
                q.push({nx, ny}); // Add to queue
                distance[nx][ny] = distance[x][y] + 1; // Update the distance
            }
        }
    }
    return -1; // If unable to reach the exit
}

int main() {
    int n, m;
    cin >> n >> m; // Input the size of the maze
    vector> maze(n, vector(m));
    
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> maze[i][j]; // Input the maze
        }
    }

    cout << bfs(maze, n, m) << endl; // Output the result
    return 0;
}
    

Code Explanation

The code uses a 2D vector to represent the maze and calculates the distance to the exit using BFS.
The main components are:

  • Queue: Used to store the currently exploring nodes to determine the next moving node.
  • Distance Array: Records the distance to each node to avoid revisiting already visited nodes.
  • Direction Arrays: The dx and dy arrays are set to enable movement in the Up, Down, Left, Right directions.

When the program runs, it performs BFS starting from the starting point, exploring all adjacent nodes.
When reaching the exit, it returns the length to that point; if it cannot be reached, it returns -1.

Time Complexity

The time complexity is O(n * m) because each node is visited once.
The space complexity is also O(n * m) due to the use of the distance array and queue.

Conclusion

In this lesson, we implemented the BFS algorithm to solve the maze exploration problem using C++.
I hope this helps you understand the basic concept of the algorithm and aids in writing actual code through practice.
Therefore, I recommend gaining experience by tackling various forms of maze exploration problems.

Creating various test cases to further improve your code is also a good learning method.