基本概念
冒泡排序(BubbleSort)的基本概念是:依次比较相邻的两个数,将小数放在前面,大数放在后面。即在第一趟:首先比较第1个和第2个数,将小数放前,大数放后。然后比较第2个数和第3个数,将小数放前,大数放后,如此继续,直至比较最后两个数,将小数放前,大数放后。至此第一趟结束,将最大的数放到了最后。在第二趟:仍从第一对数开始比较(因为可能由于第2个数和第3个数的交换,使得第1个数不再小于第2个数),将小数放前,大数放后,一直比较到倒数第二个数(倒数第一的位置上已经是最大的),第二趟结束,在倒数第二的位置上得到一个新的最大数(其实在整个数列中是第二大的数)。如此下去,重复以上过程,直至最终完成排序。
由于在排序过程中总是小数往前放,大数往后放,相当于气泡往上升,所以称作冒泡排序。
//C++实现代码
#include <iostream>
using namespace std;
void bubbleSort (int arrays[], int size);
int main ()
{
int num[] = {5,6,9,8,7,2,3,15,26,3,12,-5,-2,16,1,10};
int num_i=sizeof(num) / sizeof(int); //取数组成员数。读取文件长度,然后用长度除以数组元素大小就是个数了。
cout << "初始数据为:";
for (int i = 0; i < num_i; i++)
cout << num[i] << " ";
cout << endl;
bubbleSort(num, num_i);//使用冒泡排序
cout << "排序之后:";
for (int j = 0; j <num_i; j++)
cout << num[j] << " ";
cout << endl;
system("pause");
return 0;
}
void bubbleSort (int arrays[], int size)
{
bool changed = true;
do
{
changed = false;
for (int i = 0; i < size - 1; i++)//注意:此处循环条件i < size - 1容易写错为i < size
{
if ( arrays[i] > arrays[i + 1] )
{
swap( arrays[i], arrays[i + 1]);
changed = true;
}
}
}while (changed);
}
//C#冒泡实现代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
const int N = 5;
int[] arr = new int[N];
int temp = 0;
Console.WriteLine("请输入{0}个数", N);
for (int i = 0; i < N; i++)
{
arr[i] = int.Parse(Console.ReadLine());
}
for (int j = 0; j < N - 1; j++)
{
for (int k = 0; k < N - 1 - j; k++)
{
if (arr[k] < arr[k + 1])
{
temp = arr[k];
arr[k] = arr[k + 1];
arr[k + 1] = temp;
}
}
}
Console.WriteLine("排序后的");
for (int t = 0; t < arr.Length; t++)
{
Console.WriteLine(arr[t]);
}
Console.ReadLine();
}
}
}