#include<bits/stdc++.h> #define swap(x,y) { x = x + y; y = x - y; x = x - y; } using namespace std; void bubbleSort(int arr[], int n) { int i, j; bool flag; // Outer pass for(i = 0; i < n; i++) { flag = false; // Set flag as false for(j = 0; j < n-i-1; j++) { // Compare values if( arr[j] > arr[j+1]) { swap(arr[j],arr[j+1]); flag = true; } } if(!flag) { break; } } } int main(int argv, char* argc[]) { int arr[] = {1,5,6,8,3,4,7,2,9}; int n = sizeof(arr)/sizeof(int); cout<<"Unsorted Array :"; for(int i=0;i<n;i++) // Print the Original Array cout<<arr[i]<<" "; cout<<endl; bubbleSort(arr,n); // Call for Bubble Sort Function cout<<"Sorted Array :"; for(int i=0;i<n;i++) // Print the Sorted Array cout<<arr[i]<<" "; return(0); }
In the first line of the program, we include the header file. In the second line of the code, we define a preprocessor swap that swaps two numbers. In the third line of the code, we include the standard namespace. In the fifth line of the code, we have defined a function bubbleSort that takes two arguments. In the sixth line of the code, we have declared two variables i and j of the integer data type to loop through the array. In the seventh line of the code, we have declared a boolean flag. In the ninth line of the code, we have a for loop that runs from i equals to 0. In the tenth line of the code, we have set the value of flag equals to false. In the eleventh line of the code, we have a for loop that runs up to j equals to n-i-1. In the twelfth line of the code, we have an if statement that checks if the value of arr[j] is greater than the value of arr[j+1]. In the thirteenth line of