一.排序分析:
冒泡排序(BubbleSort)的基本概念是:依次比较相邻的两个数,将小数放在前面,大数放在后面。即在第一趟:首先比较第1个和第2个数,将小数放前,大数放后。然后比较第2个数和第3个数,将小数放前,大数放后,如此继续,直至比较最后两个数,将小数放前,大数放后。至此第一趟结束,将最大的数放到了最后。在第二趟:仍从第一对数开始比较(因为可能由于第2个数和第3个数的交换,使得第1个数不再小于第2个数),将小数放前,大数放后,一直比较到倒数第二个数(倒数第一的位置上已经是最大的),第二趟结束,在倒数第二的位置上得到一个新的最大数(其实在整个数列中是第二大的数)。如此下去,重复以上过程,直至最终完成排序。
二.代码(C++)
// sort.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<assert.h>
#include<iostream>
using namespace std;
#define NUM 10
void Bubble_Sort(int *a,int n);
int _tmain(int argc, _TCHAR* argv[])
{
int *a=new int[NUM];
for (int i = 0; i < NUM; i++)
{
cin>>a[i];
}
cout<<endl;
//Insert_sort(a,10);
Bubble_Sort(a,10);
for (int j = 0; j < NUM; j++)
{
cout<<a[j]<<" ";
}
cout<<endl;
return 0;
}
void Bubble_Sort(int * a,int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 1; j < n; j++)
{
if (a[j]<a[j-1])
{
int temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
}
}
}
}
三.结果截屏:
四.时间和空间复杂度及稳定性
时间复杂度:O(n2)
空间复杂度:0
稳定排序