开发者社区> 问答> 正文

编一个C++程序 创建一个选择排序法的函数模板sort 并在main()执行

如题 .

展开
收起
知与谁同 2018-07-18 14:40:53 1961 0
1 条回答
写回答
取消 提交回答
  • 写了两段代码,第一个是用冒泡排序法做的,第二个是快速排序法

    #include <iostream>
    using namespace std;

    //冒泡排序法
    template<typename T>
    void sort(T *data, int n)
    {
    int i, j;
    T hold;

    for (i = 0; i < n - 1; i++)
    {
    for (j = 0; j < n -1; j++)
    {
    if (data[j] > data[j+1])
    {
    hold = data[j];
    data[j] = data[j+1];
    data[j+1] = hold;
    }
    }
    }

    }

    int main()
    {
    int i;
    int a[] = {3, 2, 1, 5, 8 ,7};
    char b[] = {'b', 'c', 'a', 'p', 'g'};
    double c[] = {1.2, 2.1, 1.1, 1.0};

    sort(a, 6);
    for (i = 0; i < 6; i++)
    cout << a[i] << " ";
    cout << endl;

    sort(b, 5);
    for (i = 0; i < 5; i++)
    cout << b[i] << " ";
    cout << endl;

    sort(c, 4);
    for (i = 0; i < 4; i++)
    cout << c[i] << " ";
    cout << endl;

    return 0;
    }

    #include <iostream>
    using namespace std;

    //快速排序法
    template<typename T>
    void Quick_sort(T *data_ptr, int left, int right)
    {
    int low(left), high(right);
    T middle, temp;

    middle = data_ptr[(rand()%(right - left + 1)) + left]; //随机产生一个大于等于left且小于等于right的数

    do{
    while ((data_ptr[low] < middle) && (low < right)) //左扫面找出大于middle的数
    low++;

    while ((data_ptr[high]) > middle && (high > left)) //右扫面找出小于middle的数
    high--;

    //数据交换
    if (low <= high)
    {
    temp = data_ptr[low];
    data_ptr[low] = data_ptr[high];
    data_ptr[high] = temp;
    low++;
    high--;
    }

    }while(low <= high); //当下标交错时停止,结束一次排序

    //当左边有部分值的时候(left<high),递归左边
    if (left < high)
    Quick_sort(data_ptr, left, high);

    //当右边有部分值的时候(right > low),递归右边
    if (right > low)
    Quick_sort(data_ptr, low, right);
    }

    int main()
    {
    int i;
    int a[] = {3, 2, 1, 5, 8 ,7};
    char b[] = {'b', 'c', 'a', 'p', 'g'};
    double c[] = {1.2, 2.1, 1.1, 1.0};

    Quick_sort(a, 0, 5);
    for (i = 0; i < 6; i++)
    cout << a[i] << " ";
    cout << endl;

    Quick_sort(b, 0, 4);
    for (i = 0; i < 5; i++)
    cout << b[i] << " ";
    cout << endl;

    Quick_sort(c, 0, 3);
    for (i = 0; i < 4; i++)
    cout << c[i] << " ";
    cout << endl;

    return 0;
    }
    2019-07-17 22:50:31
    赞同 展开评论 打赏
问答分类:
C++
问答地址:
问答排行榜
最热
最新

相关电子书

更多
使用C++11开发PHP7扩展 立即下载
GPON Class C++ SFP O;T Transce 立即下载
GPON Class C++ SFP OLT Transce 立即下载