Answer to Question #212681 in C++ for champu

Question #212681

Bubble sort is an algorithm to sort a 1D array in ascending order. Firstly, explain bubble sort

and then write a C++ program by using the concept of templates to sort and display any type

of 1D array.


1
Expert's answer
2021-07-02T04:11:02-0400

Bubble Sort is a sorting algorithm where adjacent elements are swapped if they are in wrong order.

#include <bits/stdc++.h>
using namespace std;
 
void swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}


void bubbleSort(int array1[], int n)
{
    for (int i = 0; i < n-1; i++)    
     
    for (int j = 0; j < n-i-1; j++)
        if (array1[j] > array1[j+1])
            swap(&array1[j], &array1[j+1]);
}
 
void printArray(int arr1[], int n)
{
    for (int i = 0; i < n; i++)
        cout << arr1[i] << " ";
    cout << endl;
}
 
int main()
{
    int arr2[] = {10,270,30,8,50,60,70};
    int n = sizeof(arr2)/sizeof(arr2[0]);
    bubbleSort(arr2, n);
    cout<<"Sorted array: \n";
    printArray(arr2, n);
    return 0;
}
 

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS