How to implement the bubble sort algorithm in the C language?
Bubble sort is a simple sorting algorithm that repeatedly traverses the list to be sorted, compares adjacent elements, and swaps them in ascending or descending order until no more exchanges are needed.
Here is the code for implementing the Bubble Sort algorithm in C language:
#include <stdio.h>
void bubbleSort(int arr[], int n) {
int i, j;
for (i = 0; i < n-1; i++) { // 进行 n-1 轮排序
for (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;
}
Output result:
排序后的数组:
11 12 22 25 34 64 90
The bubbleSort function in the above code takes an integer array and the length of the array as parameters, using two nested loops to iterate through the array. The first loop controls the number of passes for sorting, while the second loop compares adjacent elements and swaps their positions. The resulting array is sorted in ascending order.