大家好:
衷心希望各位点赞。
您的问题请留在评论区,我会及时回答。
一、小猪称体重
案例描述:在一个一维数组中存放了5只小猪的体重,比如:300, 350, 200, 400, 250。找出并打印最重的小猪体重。
算法:max = 0设为默认体重,逐个与小猪体重比较,若比当前 max 更大,就更新 max 的值,直至比较到最后一只小猪为止。
代码示例:
#include <iostream>
#include <Windows.h>
using namespace std;
int main(void) {
int arr[5] = { 300, 350, 200, 400, 250 };
int max = 0;//记录最重的小猪体重
cout << "5只小猪体重分别为:" << endl;
for (int i = 0; i < 5; i++) {
cout << arr[i] << '\t';
}
cout << endl;
for (int i = 0; i < 5; i++) {
if (arr[i] > max)
max = arr[i];
}
cout << "最重的小猪体重为:" << max << endl;
system("pause");
return 0;
}
运行截图:
二、数组元素逆置
案例描述:请声明5个元素的数组,并将元素逆置。比如:原数组元素为1,3,2,4,5;逆置后输出结果为5,4,2,3,1。
算法:0号元素和4号元素互换,1号元素和3号元素互换,以此类推。
代码示例:
#include <iostream>
#include <Windows.h>
using namespace std;
int main(void) {
int arr[5] = { 1, 3, 2, 5, 4 };
cout << "逆置前,数组元素为:" << endl;
for (int i = 0; i < 5; i++) {
cout << arr[i] << '\t';
}
//开始下标
int start = 0;
//结束下标
int end = sizeof(arr) / sizeof(arr[0]) - 1;
while (start < end) {
//交换元素位置
int temp = 0;
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
//更新下标
start++;
end--;
}
cout << endl;
cout << "逆置后,数组元素为:" << endl;
for (int i = 0; i < 5; i++) {
cout << arr[i] << '\t';
}
cout << endl;
system("pause");
return 0;
}
运行截图:
三、冒泡排序
案例描述:最常用的排序算法,对数组元素顺序进行排序。
算法:1、比较相邻的元素,如果第一个比第二个大,就交换它们两个的顺序;2、对每一对相邻的元素做同样的工作,执行完毕以后,找到第一个最大值;3、重复上述步骤,每一趟的比较次数减1,直至不再需要比较。
代码示例:
#include <iostream>
#include <Windows.h>
using namespace std;
int main(void) {
int arr[10] = { 4, 2, 8, 0, 5, 7, 1, 3, 9, 4 };
cout << "冒泡排序前,数组元素为:" << endl;
for (int i = 0; i < 10; i++) {
cout << arr[i] << '\t';
}
cout << endl;
//共有几对相邻元素:元素总个数 - 1
for (int i = 0; i < 10 - 1; i++) {
for (int j = 0; j < 10 - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = 0;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
cout << "冒泡排序后,数组元素为:" << endl;
for (int i = 0; i < 10; i++) {
cout << arr[i] << '\t';
}
cout << endl;
system("pause");
return 0;
}
运行截图: