full stack developer
#include <iostream>
using namespace std;
// Function to swap two numbers
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
// Function to perform bubble sort
void bubbleSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
}
}
}
}
// Function to print an array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int arr[] = {64, 25, 12, 22, 11};
int size = sizeof(arr) / sizeof(arr[0]);
cout << "Original array: ";
printArray(arr, size);
bubbleSort(arr, size);
cout << "Sorted array: ";
printArray(arr, size);
return 0;
}
Explanation:
#include <iostream>
: Includes the input/output stream library for handling input and output.using namespace std;
: Allows usage of elements from the standard C++ library (such as cout, cin) without explicitly specifying the namespace.void swap(int &a, int &b)
: Defines a functionswap
that takes references to two integers and swaps their values.void bubbleSort(int arr[], int size)
: Defines a functionbubbleSort
that implements the bubble sort algorithm to sort an array of integers.void printArray(int arr[], int size)
: Defines a functionprintArray
to print the elements of an integer array.int main()
: Entry point of the program.int arr[] = {64, 25, 12, 22, 11};
: Declares an integer array with initial values.int size = sizeof(arr) / sizeof(arr[0]);
: Calculates the number of elements in the array.cout << "Original array: ";
: Outputs a message to indicate the original array is being printed.printArray(arr, size);
: Calls theprintArray
function to print the original array.bubbleSort(arr, size);
: Calls thebubbleSort
function to sort the array.cout << "Sorted array: ";
: Outputs a message to indicate the sorted array is being printed.printArray(arr, size);
: Calls theprintArray
function to print the sorted array.return 0;
: Indicates successful completion of the program.