# C最值交换排序

2020-03-15 16:58:42

## 1 回答

TiCRACK

TA贡献1条经验 获得超1个赞

#include<iostream>

using namespace std;

int foundmax(int num[])
{
int max = num[0];
for (int i = 0;i < 5;i++)
{
if (num[i] > max)
max = num[i];
}
int i;
for (i = 0;i < 5;i++)
{
if (max == num[i])
break;
}
return i;
}

void swap(int &a, int &b)
{
int temp = 0;
temp = a;
a = b;
b = temp;
}

int foundmin(int num[])
{
int min = num[0];
for (int i = 0;i < 5;i++)
{
if (num[i] < min)
min = num[i];
}
int i;
for (i = 0;i < 5;i++)
{
if (min == num[i])
break;
}
return i;
}
int main(void)
{
cout << "Please input one number" << endl;
int num1[1];
cin >> num1[0];
cout << "Please input five number" << endl;
int num2[5];
for (int i = 0;i < 5;i++)
{
cin >> num2[i];
}
int i = foundmin(num2);
swap(num2[i], num2[0]);
int j = foundmax(num2);
swap(num2[j], num2[4]);
for (int i = 0;i < 5;i++)
{
cout << num2[i]<<" ";
}
return 0;
}

1 反对 回复 2020-03-16
• 一只先飞的笨鸟
多谢多谢 我还是看的一脸懵 看来还要好好修炼一下
• TiCRACK
#include<iostream> using namespace std; template<class T> int foundmax(T num[]) { T max = num[0]; for (int i = 0;i < 5;i++) { if (num[i] > max) max = num[i]; } int i; for (i = 0;i < 5;i++) { if (max == num[i]) break; } return i; } template<class T> void swapnum(T &a, T &b) { T temp = 0; temp = a; a = b; b = temp; } template<class T > int foundmin(T num[]) { T min = num[0]; for (int i = 0;i < 5;i++) { if (num[i] < min) min = num[i]; } int i; for (i = 0;i < 5;i++) { if (min == num[i]) break; } return i; } int main(void) { cout << "Please input one number" << endl; int num1[1]; cin >> num1[0]; cout << "Please input five number" << endl; int num2[5]; for (int i = 0;i < 5;i++) { cin >> num2[i]; } int i = foundmin<int>(num2); swapnum<int>(num2[i], num2[0]); int j = foundmax<int>(num2); swapnum<int>(num2[j], num2[4]); for (int i = 0;i < 5;i++) { cout << num2[i]<<" "; } return 0; }
• TiCRACK
这是用模板的，什么整数小数都可以变

• 1 回答
• 0 关注
• 1321 浏览

0/150