Chowpk 2019-07-04 21:05 采纳率: 100%
浏览 231
已采纳

选择排序算法不知道出什么问题了

求助,不知道算法有什么问题
谢谢了

#ifndef PCH_H
#define PCH_H

// TODO: 添加要在此处预编译的标头
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cstdlib>
#endif //PCH_H

using namespace std;

#include "pch.h"

template <typename T>

void sort(T arr[]) {
    int length = sizeof(arr) / sizeof(T);   //数组长度
    T temp; //临时
    T i, j; //自变量
    T max;  //交换时选取的最大值,开始时应赋予第一个数的值
    for (i = 0; i < length; i++) {
        max = arr[i];
        for (j = i + 1; j < length; j++) {
            if (arr[j] > max) {
                temp = max;
                max = arr[j];
                arr[j] = temp;
            }
        }
        temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}

int main() {
    int a[10];
    for (int i = 0; i <= 9; i++)
        cin >> a[i];
    sort(a);
    for (int i = 0; i <= 9; i++)
        cout << a[i];
}
  • 写回答

1条回答 默认 最新

  • threenewbee 2019-07-04 22:00
    关注

    函数里数组退化为指针,不能用sizeof取长度
    你的排序算法也没有写对

    // Q768219.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    
    #include <iostream>
    #include <iomanip>
    #include <cstdio>
    #include <cstdlib>
    
    using namespace std;
    
    template <typename T>
    
    void sort(T arr[], int n) {
        int length = n;   //数组长度
        T temp; //临时
        int i, j; //自变量
        int max;  //交换时选取的最大值,开始时应赋予第一个数的值
        for (i = 0; i < length; i++) {
            max = i;
            for (j = i + 1; j < length; j++) {
                if (arr[j] > arr[max]) {
                    max = j;
                }
            }
            temp = arr[i];
            arr[i] = arr[max];
            arr[max] = temp;
        }
    }
    
    int main() {
        int a[10];
        for (int i = 0; i <= 9; i++)
            cin >> a[i];
        sort(a, 10);
        for (int i = 0; i <= 9; i++)
            cout << a[i] << " ";
    }
    
    

    4 5 8 1 5 3 7 11 2 4
    11 8 7 5 5 4 4 3 2 1 Press any key to continue . . .

    问题解决请点采纳

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊