How to implement the bubble sort algorithm in the C language?
Bubble sort is a simple sorting algorithm that works by repeatedly stepping through the list, comparing each pair of adjacent items and swapping them if they are in the wrong order.
Here is an example code of implementing the bubble sort algorithm using the C language.
#include <stdio.h>
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// 交换相邻元素
int 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]);
bubbleSort(arr, n);
printf("排序后的数组:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
In the above code, we have defined a bubbleSort function to implement bubble sort. The outer loop controls the number of sorting rounds, while the inner loop compares and swaps adjacent elements. If the previous element is greater than the next element, they are swapped. Through these comparisons and swaps, the largest element will gradually “bubble” to the end of the array.
In the main function, we define an integer array arr and obtain the length of the array using the sizeof operator. Then we call the bubbleSort function to sort the array and print the sorted result.
Running the above code will produce the following output:
排序后的数组:
11 12 22 25 34 64 90
It can be seen that the elements in the array have been arranged in ascending order.