Group
Arrays and Vectors in C++
Objective
1. Create a function that takes an array and its size as input.
2. Implement a sorting algorithm to rearrange the numbers in ascending order.
3. You can use a simple sorting algorithm such as Bubble Sort.
4. Print the sorted array to verify the result.
5. Ensure that the output displays the numbers from the smallest to the largest.
Create a program that sorts an array of numbers from smallest to largest.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include iostream for input and output
using namespace std; // Use the standard namespace
// Function to sort an array in ascending order using Bubble Sort
void sortArray(int arr[], int size) {
// Loop through each element in the array
for (int i = 0; i < size - 1; i++) {
// Loop through the array again, up to the last unsorted element
for (int j = 0; j < size - i - 1; j++) {
// If the current element is greater than the next, swap them
if (arr[j] > arr[j + 1]) {
// Swap the elements
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// Function to print the elements of the array
void printArray(int arr[], int size) {
// Loop through the array and print each element
for (int i = 0; i < size; i++) {
cout << arr[i] << " "; // Print each number followed by a space
}
cout << endl; // Print a newline after the array
}
int main() {
// Define an array of numbers to be sorted
int numbers[] = {34, 12, 5, 9, 27, 43};
int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate the size of the array
// Call the sorting function
sortArray(numbers, size);
// Print the sorted array
cout << "Sorted array: ";
printArray(numbers, size);
return 0; // End of program
}
Output
Sorted array: 5 9 12 27 34 43