With the help of sorting we arrange elements in some logical order.

**Bubble Sort**

Let us arrange elements in ascending order.

**Steps involved:**

- Compare 1st element with 2nd.
- If first element is greater than 2nd element then swap them.
- Compare 2nd element with 3rd.
- If 2nd element is greater than 3rd then swap them.
- Compare 3rd element with 4rth and so on.

On **first iteration **we get the largest element bubbled up. Similarly, on **second iteration** we get 2nd last item bubbled up.

**How to calculate the length of an array**

- sizeof(a) will return the total bytes allocated to an array.
- To get the length divide it by size of any element.

int len = sizeof(a)/sizeof(a[0])

- We need two loop.
- We want n items to get bubbled up.
- In each iteration we are comparing each element with the next element so we need (n-1) comparisons each time.

#include <stdio.h>
#include <string.h>
main()
{
int a[] = {23, 34, 12, 67, 5, 9};
int len = sizeof(a)/sizeof(a[0]), temp, i, j;
for(j = 0;j<len;j++){
for(i =0; i<len-1;i++){
if(a[i]>a[i+1]){
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
}
}
for(i=0;i<len;i++){
printf("%d\n", a[i]);
}
}

**output:**

**Complexity**: We iterate n times no matter in which order elements are arranged in array. In each iteration we do (n-1) comparisons.

So the best, worse and average time would be **O(n^2).**