- C++ Programming Examples
- C++ Programming Examples
- C++: Hello World
- C++: Get Input
- C++: Print Integer
- C++: Add two numbers
- C++: Add, Sub, Multiply, Div
- C++: Add Digits
- C++: Find Average and Percentage
- C++: Find Arithmetic Mean
- C++: Sum of n Natural Numbers
- C++: Sum of n Numbers
- C++: Square's Area and Perimeter
- C++: Rectangle's Area and Perimeter
- C++: Triangle's Area and Perimeter
- C++: Area and Circumference
- C++: Find Simple Interest
- C++: Fahrenheit to Celsius
- C++: Celsius to Fahrenheit
- C++: Print Prime Numbers
- C++: Reverse a Number
- C++: Swap Two Numbers
- C++: Print Multiplication Table
- C++: Find Factorial of a Number
- C++: Find Factors of a Number
- C++: Find HCF and LCM
- C++: Create a Calculator
- C++: Count Digits in a Number
- C++: First and Last Digit Sum
- C++: Product of Number Digits
- C++: Sum of Squares of Digits
- C++: Interchange Digits of Number
- C++ if-else Programs
- C++: Check Even or Odd
- C++: Check Prime or Not
- C++: Check Alphabet or Not
- C++: Check Vowel or Not
- C++: Check Leap Year or Not
- C++: Check Reverse equals Original
- C++: Check Perfect Number
- C++: Check Palindrome or Not
- C++: Check Armstrong or Not
- C++: Divisibility Test
- C++: Find Labor Wage
- C++: Find Discounted Price
- C++: Find Shipping Charge
- C++: Find Telephone Bills
- C++: Calculate Student Grade
- C++: Largest of Two Numbers
- C++: Largest of Three Numbers
- C++ Number Conversion
- C++: Decimal to Binary
- C++: Decimal to Octal
- C++: Decimal to Hexadecimal
- C++: Binary to Decimal
- C++: Binary to Octal
- C++: Binary to Hexadecimal
- C++: Octal to Decimal
- C++: Octal to Binary
- C++: Octal to Hexadecimal
- C++: Hexadecimal to Decimal
- C++: Hexadecimal to Binary
- C++: Hexadecimal to Octal
- C++ Pattern Programs
- C++: Pattern Programs
- C++: Print Diamond Pattern
- C++: Print Floyd's Triangle
- C++: Print Pascal's Triangle
- C++ Array Programs
- C++: 1D Array Program
- C++: Linear Search
- C++: Binary Search
- C++: Largest Element in an Array
- C++: Smallest Element in an Array
- C++: Find Second Largest Element
- C++: Find Second Smallest Element
- C++: Sum of All Elements
- C++: Multiply All Elements
- C++: Element in Even Position
- C++: Element in Odd Position
- C++: Print Even Numbers in Array
- C++: Print Odd Numbers in Array
- C++: Count Even or Odd Numbers
- C++: Sum of Even or Odd Numbers
- C++: Count Positive, Negative, Zero
- C++: Reverse an Array
- C++: Insert an Element
- C++: Delete an Element
- C++: Merge two Arrays
- C++: Bubble Sort
- C++: Selection Sort
- C++: Insertion Sort
- C++: Common Elements
- C++: 2D Array Programs
- C++: Add Two Matrices
- C++: Subtract Two Matrices
- C++: Transpose Matrix
- C++: Multiply Two Matrices
- C++: 3D Array Programs
- C++ String Programs
- C++: Print String
- C++: Find String Length
- C++: Compare Two Strings
- C++: Copy String
- C++: String Concatenation
- C++: Reverse a String
- C++: Delete Vowels from a String
- C++: Delete a Word from a String
- C++: Count Characters in a String
- C++: Count Words in a String
- C++: Frequency of Words
- C++: Remove Spaces from Strings
- C++: Sort a String
- C++: Uppercase to Lowercase
- C++: Lowercase to Uppercase
- C++: Swap Two Strings
- C++: Check the Anagram or Not
- C++: Capitalize All Words in a String
- C++: Get Numbers from a String
- C++ File Programs
- C++: Read a File
- C++: Write Content to a File
- C++: Append Data to a File
- C++: Read and Display File
- C++: Copy a File
- C++: Merge Two Files
- Count Characters in a File
- C++: Capitalize Every Word
- C++: List Files in Directory
- C++: Delete a File
- C++: Encrypt and Decrypt a File
- C++ Misc Programs
- C++: Print ASCII Value
- C++: Add Binary Numbers
- C++: Generate Random Numbers
- C++: Print a Smiling Face
- C++: Days into Years and Months
- C++: Add Two Numbers using Pointer
- C++: Print Fibonacci Series
- C++: Generate Armstrong Numbers
- C++: Find nCr and nPr
- C++: Get IP Address
- C++: Print Date and Time
- C++: Shutdown and Restart Computer
- C++ Programming Tutorial
- C++ Tutorial
C++ Program for Bubble Sort
In this article, you will learn about and get code for implementing the bubble sort technique in a C++ program. That is, you'll get the code for how to sort an array in ascending order using the bubble sort technique. The bubble sort program is created with the following approaches:
- Simple Bubble Sorting Program
- prints an array after each sort using the bubble sort algorithm
- Bubble Sort Program using a User-Defined Function
But before starting the program, if you're not aware of it, you can follow bubble sort to understand its logic with an example.
Bubble Sort in C++
To sort an array in ascending order using bubble sort in C++ programming, you have to ask the user to enter the array size and its elements. Now, use the bubble sort method to sort the array elements and show the sorted array on the screen, as shown in the next program.
#include<iostream> using namespace std; int main() { int n, i, arr[50], j, temp; cout<<"Enter the Size (max. 50): "; cin>>n; cout<<"Enter "<<n<<" Numbers: "; for(i=0; i<n; i++) cin>>arr[i]; cout<<"\nSorting the Array using Bubble Sort Technique..\n"; for(i=0; i<(n-1); i++) { for(j=0; j<(n-i-1); j++) { if(arr[j]>arr[j+1]) { temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } cout<<"\nArray Sorted Successfully!\n"; cout<<"\nThe New Array is: \n"; for(i=0; i<n; i++) cout<<arr[i]<<" "; cout<<endl; return 0; }
This program was built and runs under the Code::Blocks IDE. Here is the initial snapshot of the sample run:
Now enter the size, say 5, and then its elements as 5, 1, 4, 2, 3. Press the ENTER key, and the list gets sorted in ascending order as shown in the final snapshot of the sample run given below:
If the user enters the size of the array as 5, and its elements as 5, 1, 4, 2, 3, then the dry run of the above program goes like this:
- because the size is 5. Therefore, n=5
- And all the 5 elements gets initialized in the array arr[] in a way that arr[0] = 5, arr[1] = 1, arr[2] = 4, arr[3] = 2, and arr[4] = 3.
- Using a for loop, initially i = 0 and checks whether it is less than n-1 or not.
- Because the condition (i<(n-1) or 0<(5-1) or 0<4) evaluates to be true, therefore program flow goes inside the loop
- Inside the loop, there is another for loop, and j is initially equal to 0, and the condition j<(n-i-1) or j<(5-0-1) or j<4 evaluates to be true. Therefore, program flow goes inside this loop.
- And checks the if block's condition, that is, arr[j]>arr[j+1] or arr[0]>arr[1] or 5>1 evaluates to true, program flow enters the if block and executes all three statements.
- After executing all three statements, the element at index j gets swapped with the element at index j+1.
- Now arr[0]=1 and arr[1]=5, and the rest of the three elements will be at the same index.
- Now program flow goes to the updating part of the inner for loop and increments the value of j. Now j=1
- Again checks the condition, that is j<(n-i-1) or 1<(5-0-1) or 1<4 evaluates to be true, therefore program flow again goes inside the loop and checks the condition of if block
- If the condition evaluates to be true, then process the three statements; otherwise, update the value of j and checks the condition.
- Continue in a similar manner with the updated value until the outer for loop condition evaluates to false.
- If the condition of the outer for loop evaluates to be false, then program flow exits the loop.
- Now that the array arr[] gets sorted, just print it.
After each sort, print the array
Let's make another program that will dispel almost all of your concerns about bubble sort. This program prints the array after each sort. Take a deep look at all the arrays after each sort.
#include<iostream> using namespace std; int main() { int i, arr[10], j, temp; cout<<"Enter 10 Elements: "; for(i=0; i<10; i++) cin>>arr[i]; cout<<endl; for(i=0; i<9; i++) { for(j=0; j<(10-i-1); j++) { if(arr[j]>arr[j+1]) { temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } cout<<"Step "<<i+1<<": "; for(j=0; j<10; j++) cout<<arr[j]<<" "; cout<<endl; } cout<<endl; return 0; }
Here is the initial snapshot of the sample run:
Now enter any 10 elements in random order to sort them in ascending order. Here I've entered 10 elements in descending order, say 10, 9, 8, 7, 6, 5, 4, 3, 2, 1. After supplying all 10 elements, press ENTER to get the output as given in the final snapshot here:
Note: The last array, or the array at the last step (step no. 9), is a sorted array.
Bubble Sort in C++ using a Function
This is the last program on bubble sort. This program is created using the function bubbleSort(). The function receives the array as its argument and sorts it in ascending order.
#include<iostream> using namespace std; void bubbleSort(int []); int main() { int i, arr[10]; cout<<"Enter 10 Elements: "; for(i=0; i<10; i++) cin>>arr[i]; bubbleSort(arr); cout<<"\nThe New Sorted Array is: \n"; for(i=0; i<10; i++) cout<<arr[i]<<" "; cout<<endl; return 0; } void bubbleSort(int arr[]) { int i, j, temp; for(i=0; i<9; i++) { for(j=0; j<(10-i-1); j++) { if(arr[j]>arr[j+1]) { temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } }
Here is its sample run:
The same program in different languages
« Previous Program Next Program »