1. Introduction
Sorting is one of the fundamental operations in computer science. It refers to arranging data in a particular format or order. In this blog post, we'll delve into creating a C++ program that sorts an array in ascending order using the Bubble Sort algorithm, a beginner-friendly sorting algorithm.
2. Program Overview
1. Define and initialize the array.
2. Use the Bubble Sort technique to arrange elements in increasing order.
3. Display the sorted array.
3. Code Program
#include <iostream>
using namespace std;
int main() {
int n, temp;
// Input number of elements
cout << "Enter the number of elements in the array: ";
cin >> n;
int arr[n];
// Input array elements
cout << "Enter the elements of the array:" << endl;
for(int i=0; i<n; i++) {
cin >> arr[i];
}
// Bubble Sort algorithm
for(int i=0; i<n-1; i++) {
for(int j=0; j<n-i-1; j++) {
if(arr[j] > arr[j+1]) {
// Swapping using temporary variable
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
// Displaying the sorted array
cout << "Sorted array in ascending order:" << endl;
for(int i=0; i<n; i++) {
cout << arr[i] << " ";
}
return 0;
}
Output:
For an array: 64, 34, 25, 12, 22, 11, 90 Sorted array in ascending order is: 11 12 22 25 34 64 90
4. Step By Step Explanation
1. Array Initialization: We take the size of the array and its elements as input from the user.
2. Bubble Sort: It is a simple sorting algorithm that repeatedly steps through the list, compares adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted.
3. Display: After sorting the array using Bubble Sort, we display the sorted array in ascending order.
The Bubble Sort algorithm, though not the most efficient, is a good starting point for understanding the basics of sorting algorithms in computer science.
Comments
Post a Comment
Leave Comment