Detailed explanation of bubble sorting method

Hello everyone, today we are going to learn the bubble sorting method in C language. In C language, we often have a trouble, that is, we give you an array with n numbers stored in it and ask you to sort it. At this time Many friends may be worried about how we can sort it quickly. This is the content bubble sorting method we are going to learn today.

bubble sort

1. First we give a set of out-of-order numbers to the array.

int arr[10] = {
    
     25,35,68,79,21,13,98,7,16,62 };
	int i = 0;
	int j = 0;
	int t;

2. Next we analyze the sorting. At the beginning we have ten numbers. It takes nine times to compare the first element with the following ones. After nine comparisons and sorting, it is the next one's turn to compare and sort the next numbers, because The first number has already been compared with this number in the first round of comparison, so this number only needs to be compared and sorted with the other eight numbers in this round, and so on for the subsequent numbers. So loop nesting is used here. The first loop represents the number of rounds to be compared, and the second loop represents the number of comparisons.
Insert image description here
Next see the code:

#include<stdio.h>
int main()
{
    
    
	int arr[10] = {
    
     25,35,68,79,21,13,98,7,16,62 };
	int i = 0;
	int j = 0;
	int t;
	for (i = 0; i < 9; i++)
	{
    
    
		for(j=0;j<9-1-i;j++)
			if (arr[j] > arr[j + 1])
			{
    
    
				t = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = t;
			}
	}
	

3. Finally, use a loop to print out the array.

for (i = 0; i < 10; i++)
		printf("%d ", arr[i]);
	return 0;
}

Finally, take a look at the complete code and running results.

#include<stdio.h>
int main()
{
    
    
	int arr[10] = {
    
     25,35,68,79,21,13,98,7,16,62 };
	int i = 0;
	int j = 0;
	int t;
	for (i = 0; i < 9; i++)
	{
    
    
		for (j = 0; j < 10 - 1 - i; j++)
			if (arr[j] > arr[j + 1])
			{
    
    
				t = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = t;
			}
	}
	for (i = 0; i < 10; i++)
		printf("%d ", arr[i]);
	return 0;
}

Insert image description here
Okay, that’s it for today’s sharing, thank you all.

Guess you like

Origin blog.csdn.net/Lehjy/article/details/132266676