Algorithm description:

  • The basic idea of bubble sort is to compare two adjacent elements each time and swap them if they are in the wrong order.
  • If you have n numbers to sort by, you only have to put n minus 1 numbers back, which means you have to do n minus 1 operations.
  • The ith comparison only requires n minus I comparisons.

Complexity analysis:

  • The time complexity of bubble sort is O(N2)O(N^2)O(N2).
  • This is a very high time complexity.

Code part:

#include <stdio.h>
int main(a)
{
	int a[101];// Support 100 comparisons
	int i, j, t, n;
	printf("Please enter how many numbers you want to sort :");
	scanf_s("%d", &n);
	for (i = 1; i <= n; i++)
		scanf_s("%d", &a[i]);
	// The bubbling core
	for (i = 1; i <= n - 1; i++)
		for (j = 1; j <= n - i; j++)
		{
			if (a[j] < a[j + 1])// Sort from largest to smallest
			{
				t = a[j];
				a[j] = a[j + 1];
				a[j + 1] = t; }}for (i = 1; i <= n; i++)
		printf("%d ", a[i]);
	getchar();
	getchar();
	return 0;
 
}
Copy the code

Input:

5, 2, 5, 3, 8Copy the code

Output:

8, 5, 5, 3, 2Copy the code

Conclusion:

Disadvantages:

  • Time complexity is too high. // Bubble sort is O(N2)O(N^2)O(N2).

Advantages:

  • Solved the problem of bucket sort wasting space.