冒泡排序

//  Bubble.cpp : Defines the entry point for the console application.
//
// 冒泡排序是对相临元素进行比较,如果左边的元素大于右边则交换,
//   这样一直持续下去。

#include 
" stdafx.h "
#include 
< iostream >
#include 
< algorithm >
using   namespace  std;

// 第一种方法
template  < class  T >
void  Bubble(T a[],  int  n)
{
    
for(int i = 0; i < n-1; i++)//注意是n-1
        if(a[i] > a[i+1])swap(a[i], a[i+1]);
}


template
< class  T >
void  BubbleSort(T a[],  int  n)
{
    
for(int i = n; i >1; i--)
        Bubble(a, i);
}

// 第二种方法,改进方法。

// 冒泡排序的改进版:如果在一次冒泡的过程中没有发生元素交换,
// 说明数组已经按序排列,没必要进行冒泡排序。
template < class  T >
bool  Bubble(T a[],  int  n)
{
    
bool swapped = false;
    
for(int i = 0; i < n-1; i++)
        
if(a[i] > a[i+1])
            swap(a[i], a[i
+1]);
        swapped 
= true;//发生了交换
        return swapped;
}

template 
< class   T >
void  BubbleSort(T a[],  int  n)
{
    
for(int i = n; i > 1&& Bubble(a,i); i--);
}


int  main( int  argc,  char *  argv[])
{   

    
int a[] = {4,7,8,99,2,4,85,1,47,26};
    
const int icon = sizeof(a)/ sizeof(&a[0]);
    BubbleSort(a,icon);
    
for(int i = 0; i < icon; i++)
        cout
<<a[i]<<endl;

    
return 0;
}

 

你可能感兴趣的:(Algorithm,Class,iostream)