Bubble Sort in C: Step-by-Step Guide with Code
Bubble Sort is a simple sorting algorithm that repeatedly goes through the list to be sorted, comparing each pair of adjacent elements and swapping them if they are in the wrong order, until the entire list becomes sorted.
Here is an example code of using bubble sort in 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]) {
// 交换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("排序后的数组:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
In the code above, we have defined a function called bubbleSort to perform the bubble sort. In the main function, we create an integer array and call the bubbleSort function to sort it. Finally, we print the sorted array.
The output of this sample code is: 11 12 22 25 34 64 90, which is the original array sorted in ascending order.