码迷,mamicode.com
首页 > 编程语言 > 详细

冒泡排序

时间:2017-04-02 15:41:07      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:name   typename   str   blog   include   tmp   bubble   return   log   

冒泡排序

冒泡排序就是将数据两两比较,将大的或者晓得往后排,排序一次得到一个最大值或者最小值

代码主要把握比较趟数和两两比较次数

for主要作用是控制循环次数让代码执行下去

#include <iostream>
using namespace std;
template<typename T> 
void  bubble_sort    (T * array, int len,bool ascending)
{

        T tmp = 0;
        if(ascending)
        {
            for(int i = 0; i < len-1; i ++)
            {
                for(int j = 0; j < len-i-1; j++)
                {
                    if(array[j]<=array[j+1])
                        continue;
                    else
                    {
                        tmp = array[j];
                        array[j] = array[j+1];
                        array[j+1] = tmp;
                    } 
                }
        
            }
        }
        else
        {
            for(int i = 0; i < len-1; i ++)
            {
                for(int j = 0; j < len-i-1; j++)
                {
                    if(array[j]>=array[j+1])
                        continue;
                    else
                    {
                        tmp = array[j];
                        array[j] = array[j+1];
                        array[j+1] = tmp;
                    } 
                }
        
            }
    
        }

}


int main()
{
    float data[8];
    for(int i = 0; i<8;i++)
    cin>>data[i];

    cout<<"data"<<endl;

    for(int i = 0; i<8;i++)
    cout<<data[i]<<endl;

    bubble_sort<float>(data,8,false);

    cout<<"sorted data"<<endl;
    for(int i = 0; i<8;i++)
    cout<<data[i]<<endl;
    return 0;
}

 

冒泡排序

标签:name   typename   str   blog   include   tmp   bubble   return   log   

原文地址:http://www.cnblogs.com/hong2016/p/6659118.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!