Sorting array is a fundamental problem in computer science and various sorting algorithms are available for this purpose. One such state-forward and effective algorithm is Bubble Sort. In this article, we are going to use Bubble Sort to sort an array in ascending order.
Table of Contents
How Bubble Sort Works?
The Bubble Sort algorithm is simple to understand and implement. It works by repeatedly swapping adjacent elements if they are in the wrong order, Thus Bubbling the largest or smallest elements towards the end or start of the array.
Sorting an Array in Ascending Order in C
# include<stdio.h>
void buubleSort(int arr[], int n){
int temp;
for(int i=0;i<n;i++){
for(int j=0;j<(n-i-1);j++){
if(arr[j]>arr[j+1]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
void main(){
int array[] = {6, 7,8,4,2, 67,23,56};
int n = sizeof(array)/sizeof(array[0]);
printf("Array before sorting\n");
for(int i =0;i<n;i++){
printf("%d ", array[i]);
}
buubleSort(array,n);
printf("\nArray after sorting\n");
for(int i =0;i<n;i++){
printf("%d ", array[i]);
}
}
Output
How above C Program Works
- The bubble sort function iterates through the array, compares adjacent elements, and swaps them if they are in the wrong order.
- It continues the process for multiple passes until the entire array is sorted.
6 thoughts on “Sorting an Array in Ascending Order”