当前位置:网站首页>[implementation of bubble sorting]

[implementation of bubble sorting]

2022-06-11 02:36:00 Cat star people who love Durian


1、 Bubble sort implementation

Tips : The time complexity of bubble sort is :F(N)=N*(N-1)/2

#include<stdio.h>

int main()
{
    
	int arr[10] = {
     1,6,4,3,9,5,0,7,2,8 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	for (int i = 0; i < sz - 1; i++)
	{
    
		int flag = 0;
		for (int j = 0; j < sz - 1 - i; j++)
		{
    
			if (arr[j] > arr[j + 1])
			{
    
				int tmp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = tmp;
				flag = 1;
			}
		}
		if (flag == 0)
			break;
	}
	for (int i = 0; i < sz; i++)
	{
    
		printf("%d ", arr[i]);
	}
	return 0;
}

Running results :
 Insert picture description here
Add a picture that is convenient for drawing and understanding :
 Insert picture description here


2、 Function implementation of bubble sort

#include<stdio.h>
void BubbleSort(int* a, int n)
{
    
	for (int end = n; end > 1; --end)
	{
    
		int exchange = 0;
		for (int i = 1; i < end; ++i)
		{
    
			if (a[i - 1] > a[i])
			{
    
				int tmp = a[i - 1];
				a[i - 1] = a[i];
				a[i] = tmp;
				exchange = 1;
			}
		}
		if (exchange == 0)
			break;
	}
}

int main()
{
    
    int arr[10] = {
     1,6,4,3,9,5,0,7,2,8 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	BubbleSort(arr, sz);
	for (int i = 0; i < sz; i++)
	{
    
		printf("%d ", arr[i]);
	}

	return 0;
}

Running results :
 Insert picture description here


The above is the whole content of this article , If there are mistakes in the article or something you don't understand , Communicate more with meow bloggers . Learn from each other and make progress . If this article helps you , Can give meow bloggers a concern , Your support is my biggest motivation .

原网站

版权声明
本文为[Cat star people who love Durian]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110143215692.html