# Programming Videos

## Search

### C, C++ Program for Bubble Sort - Program, Algorithm, Time Complexity

Write a C, C++ program to implement bubble sort. Given an unsorted array, we have to write a code to sort an array using bubble sort.

## Bubble Sort

Bubble sort work by comparing each pair of adjacent elements and switching their positions if necessary. It repeats this process until all the elements are sorted.

How to swap two numbers using third variable

Time Complexity of Bubble Sort

Average case complexity O(n2)

Worst case complexity  O(n2)

Bubble sort algorithm is not good for large data set. For large data set try to use Quicksort and Mergesort.

Selection Sort Algorithm

Sorting algorithms and their time complexity

## Bubble Sort Program in C++

```#include <iostream>
using namespace std;

int main() {

int arr, n;

cout << "Enter number of elements (Max 100)\n";
cin  >> n;

cout << "Enter the values\n";

for(int i=0; i<n ;i++){
cin >> arr[i];
}

for(int j=0; j < n-1; j++) {
for(int k=0; k < n-j-1; k++) {

/* Swapping if necessary */
if(arr[k] > arr[k+1]){

int temp = arr[k];
arr[k]   = arr[k+1];
arr[k+1] = temp;
}
}
}

/* Print Sorted result. */

for(int m = 0; m < n; m++){

cout << arr[m] << endl;
}

return 0;
}

```

C, C++ Interview Questions

## Bubble Sort Program in C

```#include <stdio.h>

int main(void) {

int arr, n;

printf("Enter the number of elements (Max 100)\n");
scanf("%d",&n);

printf("Enter the values\n");

//Input array elements
for(int i = 0; i < n; i++){
scanf("%d",&arr[i]);
}

for(int j = 0; j < n-1; j++) {
for(int k = 0; k < n-j-1; k++) {

if(arr[k] > arr[k+1]){

int temp = arr[k];
arr[k]   = arr[k+1];
arr[k+1] = temp;
}
}
}

/* Print Sorted result. */

for(int m = 0; m < n; m++){

printf("%d\n", arr[m]);
}

return 0;
}

```

Output -

Enter the number of elements  :  5

Enter the values

4
2
1
6
3

After sorting
1
2
3
4
6