Here's an example implementation of the Bubble Sort Algorithm in C:
#include <stdio.h>
void bubble_sort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// swap elements
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
int i;
bubble_sort(arr, n);
printf("Sorted array: \n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
In this implementation, the bubble_sort
function takes an array of integers arr
and its size n
as input. It then performs the bubble sort algorithm by iterating over the array and comparing adjacent elements to each other. If the left element is greater than the right element, they are swapped. This process is repeated until the array is sorted.
The main
function initializes an array of integers, calls the bubble_sort
function with the array and its size, and then prints the sorted array to the console.
Asked: 2021-10-12 11:00:00 +0000
Seen: 10 times
Last updated: Oct 05 '22