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

来源:互联网 发布:网络的概念 编辑:程序博客网 时间:2024/04/29 12:43

     冒泡排序(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[n] = b[n];
//  }
  }
  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;
}


0 1