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.
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;
}
Comments
Leave a comment