- 数组-一维数组案例-元素逆置
原数组元素:1,3,2,5,4 逆置后输出结果:4,5,2,3,1
1.arr[1]是一个具体的元素,arr是数组
2.设置一个中间变量,放数
#include <iostream>
using namespace std;
int main()
{
int start = 0, end = 0, temp;
int arr[5] = { 1,3,2,5,4 };
cout << "元素逆置前的结果:" << endl;
for (int i = 0; i < 5; i++)
{
cout << arr[i] << endl;
}
end = sizeof(arr) / sizeof(arr[0]) - 1;//下标,元素数-1
while (start < end)
{
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
//下标更新
start++;
end--;
}
cout << "元素逆置后的结果:" << endl;
for (int i = 0; i < 5; i++)
{
cout << arr[i] << endl;
}
return 0;
}
- 数组-一维数组-冒泡排序
对组内元素进行排序
1.比较相邻的元素,如果第一个比第二个大,就交换他们两个。
2.对每一对相邻元素做同样的工作,执行完毕后,找到一个最大值。
3.重复以上步骤,每次比较次数-1,直到不再比较。
#include<iostream>
using namespace std;
int main()
{
int arr[9] = { 2,4,0,5,7,1,3,8,9 };
int temp;
for (int c = 0; c < 9; c++)
{
cout << arr[c] << endl;
}
cout << endl;
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9 - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] =temp;
}
}
}
for (int c = 0; c < 9; c++)
{
cout << arr[c] << endl;
}
return 0;
}
3.为什么9-1:两个数对比,只需要对比一次,九个数对比,需要对比8次
4.为什么9-i-1:每次对比完,最后一个数都已经确定了是最大数