Sorting algorithm : bubble sort in C

In this program we will use bubble sort for sorting the element of an array. Bubble sort is a widely used sorting algorithm in C. This algorithm compares two adjacent element and swap them if they are not in right order. Here we will use bubble sort for sorting an array in ascending order.

We recommend you to see our array chapter to get enough knowledge for working with array in C programming.

C program using bubble sort

``````// c program using bubble sort sorting algorithm

#include<stdio.h>
int main(){
int c, d, counter, temp, num[50];

printf("Enter how many numbers you want to sort : ");
scanf("%d",&counter);

printf("Enter all the number here : ");

for(c = 0; c < counter; c++){
scanf("%d", &num[c]);
}

for(c = counter - 2; c >= 0; c--){

for(d = 0; d <= c; d++){

if(num[d] > num[d + 1]){
temp = num[d];
num[d] = num[d + 1];
num[d + 1] = temp;
}
}
}

printf("\nElements after sorting are : \n");

for(c = 0; c < counter; c++){
printf(" %d",num[c]);
}

return 0;
}``````

Bubble sort using function in C

``````// bubble sort using function in c

#include <stdio.h>

void bSort(int arr[], int num){
int j, k, t;

for (j = 0 ; j < num - 1; j++){

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

if (arr[k] > arr[k + 1]){
t = arr[k];
arr[k] = arr[k + 1];
arr[k + 1] = t;
}

}
}
}

int main(){
int myArr[50], number, a;

printf("Enter how many integer you want to sort : ");
scanf("%d", &number);

printf("Enter all integers here : \n");

for (a = 0; a < number; a++){
scanf("%d", &myArr[a]);
}

bSort(myArr, number);

printf("\nArray after sorting is : \n");

for (a = 0; a < number; a++){
printf("%d ", myArr[a]);
}

return 0;
}``````

Output :

``````Enter how many integer you want to sort : 10
Enter all integers here :
8 22 32 4 3 6 12 38 50 15

Array after sorting is :
3 4 6 8 12 15 22 32 38 50``````