代码改变世界

排序算法

2017-05-18 17:56  sinohenu  阅读(181)  评论(0)    收藏  举报

复习一下基本的排序算法

1 冒泡排序

2 选择排序

3 插入排序

#include <iostream>
using namespace std;

void swap(int& a, int& b)
{
    a += b;
    b = a - b;
    a = a - b;
}
//冒泡排序
int BubbleSort(int a[], const int size)
{
    cout << "bubble sort......"<< endl;
    bool swapped = false;
    do
    {
        swapped = false;
        for(int i = size; i > 0; --i)
        {
            for(int j = 0; j < i -1; ++j)
            {
                if(a[j] > a[j+1])
                {
                    swap(a[j],a[j+1]);
                    swapped = true;
                }
                
            }
            
        }
    }while(swapped);

    return 0;
}
//选择排序
int SelectSort(int a[], const int size)
{
    for(int i = 0; i < size - 1; ++i)
    {
        bool swapped = false;
        int min = a[i];
        int oriMinIndex = i, curMinIndex = 0;
        for(int j = i+1; j < size; ++j)
        {
            if(min > a[j])
            {
                min = a[j];
                curMinIndex = j;
                swapped = true;
            }
        }
        if(swapped)
            swap(a[oriMinIndex], a[curMinIndex]);
    }
    return 0;
}
//插入排序
int InsertSort(int a[], const int size)
{
    for(int i = 1; i < size; ++i)//unsorted
    {
        for(int j = i-1; j >= 0; --j)//sorted
        {
            if(a[j+1] < a[j])
                swap(a[j+1], a[j]);
            else
                break;
        }
    }
    return 0;
}
int main() { int a[] = {27,11,8,49,14,27,19,5,18,35,50,32,32,18,38,18,23,32,37}; #define ARRAY_SIZE (sizeof(a)/sizeof(int)) BubbleSort(a, ARRAY_SIZE); // SelectSort(a, ARRAY_SIZE); // InsertSort(a, ARRAY_SIZE); Dump(a,ARRAY_SIZE); #ifdef WIN32 getchar(); #endif #undef ARRAY_SIZE return 0; }