您的位置:首页 > 编程语言 > C语言/C++

C/C++学习(五)冒泡排序

2015-12-10 19:21 323 查看


冒泡排序(Bubble Sort)是一种简单的排序算法。它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成


算法原理

冒泡排序算法的运作如下:(从后往前)

​1.比较相邻的元素。如果第一个比第二个大,就交换他们两个。

2.对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。

3.针对所有的元素重复以上的步骤,除了最后一个。

4.持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。



算法示例

#include <iostream>

#include <array>

#include <memory>

#include <string>

using namespace std;

class bubble_sort

{



public:

bubble_sort(int b[])

{


memcpy(a, b, 10*sizeof(int));

//  for(int n=0;n<10;n++)

//{

//      a
= b
;

//}


}


void sort(int n)

{

temp = 0;//初始化temp

for(i=0 , change=true; i<n&&change; i++)

  {

change = false;

for(j=i+1; j>0; j--)

{

if(j > 10)//数组越界处理

    {


}

else

     {

if(a[j-1]>a[j])

       {

temp = a[j-1];

a[j-1] = a[j];

a[j] = temp;


change = true;

 }

}

}

  }

}


private:

int i,j,temp;

bool change;

public:

int a[10];

};

int main()

{

//    cout << "Hello World!" << endl;

//array<int,10> arr1;

int arr1[10];

cout << "please input 10 numbers:" << endl;

for(int i=0; i<10; i++)

cin >> arr1[i];


cout << "before sort:" << endl;

for(int i=0; i<10; i++)

cout << " " << arr1[i];

cout << endl;


cout << "after sort:" << endl;

bubble_sort *b = new bubble_sort(arr1);

b->sort(10);

for(int i=0; i<10; i++)

cout << " " << b->a[i];


return 0;


}




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: