Bubble Sort in C: Sort n Numbers
Bubble sort is a simple sorting algorithm that repeatedly visits the list to be sorted, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated until the entire list is sorted.
Below is the code implementing the Bubble Sort algorithm in C language.
#include <stdio.h>
void bubbleSort(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]) {
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 this example, we define a function called bubbleSort to implement bubble sorting. Initially, we use two nested loops to iterate through the entire array. The inner loop is used to compare adjacent elements, swapping them if they are in the wrong order. The outer loop controls the number of sorting rounds. Each round, the largest number sinks to the end of the array. Finally, we call bubbleSort in the main function and print the sorted array.
In this example, the input array is {64, 34, 25, 12, 22, 11, 90}, and the sorted result is {11, 12, 22, 25, 34, 64, 90}.