• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
煎蛋啊
博客园    首页    新随笔    联系   管理    订阅  订阅
冒泡排序

冒泡排序的基本思想就是对于给定的n个元素,从第一个元素开始,依次对相邻的两个元素进行比较,当前面的元素大于后面的元素时,交换其位置,进行一轮比较和换位后,n个元素中最大的数将位于第n位,然后对前(n-1)个元素进行第二轮比较,重复该过程,直到进行比较的元素只剩下一个。

数组{36,25,48,12,25,65,43,57}

第一趟排序:[25 36 12 25 48 43 57] 65

第二趟排序:[25 12 25 36 43 48] 57 65

第三趟排序:[12 25 25 36 43] 48 57 65

第四趟排序:[12 25 25 36] 43 48 57 65

第五趟排序:[12 25 25] 36 43 48 57 65

第六趟排序:[12 25] 25 36 43 48 57 65

第七趟排序:[12] 25 25 36 43 48 57 65

 

#include "string.h"
#include "stdio.h"
#include <vector>
#include <deque>
#include<stack>
using namespace std;

class Sort{
public:

    int* bubbleSort(int* A, int n) {
        // write code here
        if(n<=0)
        {
            return 0;
        }
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<n-1-i;j++)
            {
                if(A[j]>A[j+1])
                {
                    swap(A[j],A[j+1]);
                }
            }
        }
        return A;
    }
};
int main()
{
    int array[]={3,4,5,1,2,8,7};
    Sort sort;
    int len = sizeof(array)/sizeof(array[0]);
    int* arr = sort.bubbleSort(array,len);
    for(int i=0;i<len;i++)
    {
        cout<<arr[i]<<" ";
    }
    cout<<endl;
    return 0;
}

 

posted on 2017-03-21 21:07  煎蛋啊  阅读(219)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3