牛骨文教育服务平台(让学习变的简单)

冒泡是一个程序员接触最早的一个排序算法,简单粗暴。

冒泡排序的核心思想就是:依次比较相邻的两个数,如果第一个数比第二个大就交换。

程序还是要自己动手写,这样理解得才快。

#include "stdafx.h"
#include <iostream>
#include <string>

#define SIZE(A) sizeof(A)/sizeof(*A)

using namespace std;

void bubbleSort(int a[],int size)
{
	// 两个循环来比较相邻的两个数,如果前一个比后面一个大就交换
	for (int i=0;i<size;i++)
	{
		for (int j=0;j<i;j++)
		{
			if (a[i]>a[j])
			{
				int temp = a[i];
				a[i] = a[j];
				a[j] = temp;
			}
		}
	}
}

int main() {
	
	int a[] = {2,6,8,1,0,3,4};
	int size = SIZE(a);
	for (int i=0;i<size;i++)
	{
		cout<<a[i]<<" ";
		if (i==size-1)
			cout<<endl;
	}
	// 调用冒泡排序
	bubbleSort(a,size);
	for (int i=0;i<size;i++)
	{
		cout<<a[i]<<" ";
		if (i==size-1)
			cout<<endl;
	}
	system("pause");
	return 0;
}

排序的结果: