# Write a Program in C++ & Python & Short an Array Using Bubble Sort

By | September 21, 2019

Here in this program, we will code to sort an unsorted array using bubble sort.

Bubble sort is one of the sorting algorithms we use to sort an unsorted array it has a time complexity of O(n2) where n2 is the time complexity of Average and worst case.

### Logic

In bubble sort we compare the element with its adjacent element and swap them if the adjacent element is smaller, we repeat this logic until the largest element reaches at the last end of the array.

### C++

```#include<iostream.h>
#include<stdio.h>
#include<conio.h>
void main()
{
int num,a,temp;
clrscr();
cout<<"How many elements you want to enter in the array: ";
cin>>num;
cout<<"Enter elements in the array\n";
for(int i=0; i<num; i++)
{cin>> a[i];
}
for(int k=0; k<num-1;k++)
{    for(i=0; i<num-k-1;i++)
{
if (a[i] > a[i+1])
{   temp = a[i];
a[i] =a[i+1];
a[i+1] = temp;
}
}

}
for(i=0;i<num;i++)
cout<<a[i]<< " ";
getch();
}```

Output:

```How many elements you want to enter in the array: 6

Enter the elements in the array

12
32
3
4
2
14
2 3 4 12 14 32```

### Program in Python

```arr =[]
num= int(input("How many elements you want to enter in the array: "))
print("Enter the elements in the array")

for i in range(num):
elements = int(input())
arr.append(elements)

for k in range(len(arr)):
for i in range(0, num-k-1):
if arr[i] > arr[i+1]:
arr[i],arr[i+1]=arr[i+1],arr[i]

for i in range(len(arr)):
print(arr[i],end=' ')```

Output:

```How many elements you want to enter in the array: 6

Enter the elements in the array

12
32
3
4
2
14
2 3 4 12 14 32```