Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high.
Bubble Sort Algorithm
In this algorithm,
i. traverse from left and compare adjacent elements and the higher one is placed at right side.
ii. In this way, the largest element is moved to the rightmost end at first.
iii. This process is then continued to find the second largest and place it and so on until the data is sorted.
Source Code:-
#include<stdio.h>
void BubbleSort(int *a, int n) {
int i, j, temp;
for (i=0; i<n-1; i++) {
for (j=0; j<n-i-1; j++) {
if (a[j] > a[j+1]) {
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
int main() {
int n;
printf("Enter the length of the array : ");
scanf("%d", &n);
int arr[n];
printf("Enter the elements : ");
for (int i=0; i<n; i++){
scanf("%d", &arr[i]);
}
BubbleSort(arr, n);
printf("The sorted array is :\n");
for (int i=0; i<n; i++){
printf("%d ", arr[i]);
}
return 0;
}
output:
Enter the length of the array : 5
Enter the elements : 7 3 9 1 10
The sorted array is :
1 3 7 9 10
No comments:
Post a Comment