The principle of bubble sorting is ： From left to right , Compare adjacent elements . Compare one round at a time , You will find the largest one or the smallest one in the sequence . This number will appear from the far right of the sequence .

Take sorting from small to large as an example , After the first round of comparison , The largest of all numbers will float to the far right ; After the second round of comparison , The second largest number in all numbers will float to the penultimate position …… Just compare it round by round , Finally, sort from small to large .

The code is as follows
#include<stdio.h> void Bubble_sort(int arr[], int size) { int j,i,tem; for (i
= 0; i < size-1;i ++)//size-1 Because you don't have to compare with yourself , So it's one less than the number { int count = 0; for (j = 0;
j < size-1 - i; j++) //size-1-i Because each trip will be less than one number { if (arr[j] >
arr[j+1])// This is ascending arrangement , Comparison between the previous number and the latter number , If the first number is large, change the position with the next number { tem = arr[j]; arr[j] = arr[j+1];
arr[j+1] = tem; count = 1; } } if (count == 0) // If there is no exchange position on a certain trip , Then it means that the order has been arranged , Exit the cycle directly
break; } } int main() { int arr; int i; printf(" Please enter 10 number \n"); for (i = 0; i
< 10; i++) // Receive user's value { scanf("%d", &arr[i]); } printf(" Array before sorting >"); for (i = 0; i
< 10; i++) { printf("%d ", arr[i]); } printf("\n Sorted array >"); Bubble_sort(arr,
10); for (i = 0; i < 10; i++) { printf("%d ", arr[i]); } return 0; }
It is worth noting that the definition in the function count It is to check whether the exchange of elements is carried out , It is an optimization of code

Operation results >

Technology
Daily Recommendation