algorithms

# Bubble, Selection and Insertion Sorts – C

This post presents the C program of three basic sorting techniques.

Bubble Sort:

```#include

void bubble_sort(int n, int *a)
{
int i, j, temp =0;
for(i=0; i <= n-2; i++) {
for (j=0; j<= n-2-i; j++) {
if(a[j+1]<a[j]) {
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}

int main()
{
int a[10] = {2, 6, 8, 9, 4};
int n = 5;

bubble_sort(n, a);

return 0;
}
```

Selection Sort:

```#include

void selection_sort(int n, int *a)
{
int i, j, temp =0;
int min;
for(i=0; i <= n-2; i++) {
min = i;
for (j=i+1; j<= n-1; j++) {
if(a[j]<a[min])
min = j;
}
temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}

int main()
{
int a[10] = {2, 6, 1, 11, 4};
int n = 5;

selection_sort(n, a);

return 0;
}
```

Insertion Sort:

```#include

void insertion_sort(int n, int *a)
{
int i, j;
int v;
for(i=1; i = 0 && a[j] > v)
{
a[j+1] = a[j];
j = j - 1;
}
a[j+1] = v;
}
}

int main()
{
int a[10] = {2, 6, 1, 11, 4};
int n = 5;

insertion_sort(n, a);

return 0;
}
```