排序

http://blog.youkuaiyun.com/fengzhitalker/article/details/7898804

c++实现快速排序(挖坑填数版)

无疑这种方法比本来的方法更加快捷,减少了内存开销,直接在原数组进行排序

#include <iostream>

using namespace std;

//采用挖坑法实现快速排序

template <typename T>

int quickSort2(T *const t, const int begin,const int end)

{

    if(begin >= end)

    {

        return 0;

    }

    T temp = t[begin];

    int left = begin;

    int right = end;

    while(left < right)

    {

        while(t[right] > temp && left < right)

        {

   right--;

        }

if(left != right)

        {

            t[left] = t[right];

   left++;

        }

        while(t[left] < temp && left < right)

{

   left++;

}

if(left != right)

  {

   t[right] = t[left];

     right--;

}

    } 

    t[left] = temp;

    //对确定好位置的元素的左右子数组进行排序

    quickSort2(t, begin, left - 1);

    quickSort2(t, left + 1, end);

}

template <typename T>

int printArray(T *const t, int len)

{

    for(int i = 0; i < len; i++)

    {

    cout << t[i] << ';';

    }

    cout<<endl;

}

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

{

    int c[10] = {9,4,6,1,11,4,5,3,10,0};

    quickSort2(c, 0, sizeof(c)/sizeof(int) - 1);

    printArray(c, sizeof(c)/sizeof(int));

    return 0;    

}

----------------------------------------------

 

冒泡排序和插入排序

#include <iostream>

using namespace std;

template <typename T>

//冒泡排序

int bubbleSort(T *const t, int len)

{

    for(int i = len - 1; i > 0; i--)

    {    

    for(int j = 0 ; j < i; j++)

        {

        if(t[j] > t[j + 1])

        {

            T temp = t[j];

        t[j] = t[j + 1];

        t[j + 1] = temp;

        }

    }

    }

    return 0;

}

//插入排序

template <typename T>

int insertSort(T *const t, int len)

{

    for(int i = 1; i < len; i++)

    {

    for(int j = i; j >= 1; j--)

        {

        if(t[j] < t[j - 1])

        {

            T temp = t[j - 1];

        t[j - 1] = t[j];

        t[j] = temp;

        }else

        {

        break;

        }

    }

    } 

}

template <typename T>

int printArray(T *const t, int len)

{

    for(int i = 0; i < len; i++)

    {

    cout << t[i] << ';';

    }

    cout<<endl;

}

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

{

    int c[10] = {9,4,7,6,11,4,3,2,1,0};

   // bubbleSort(c, sizeof(c)/sizeof(int));

    insertSort(c, sizeof(c)/sizeof(int));

    printArray(c, sizeof(c)/sizeof(int));

    return 0;    

}


转载于:https://my.oschina.net/floristgao/blog/312147

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值