question
Sort the elements of the array from small to large.
1. Analyze the problem
- Known: array of n integers
- Unknown: updated array
- Relationship: Sort from smallest to largest - bubble sort
2. Define variables
//二、数据定义
int n,arr[10];
3. Enter data
//三、数据输入
cin>>n;
for(int i=0;i<n;i++){
cin>>arr[i];
}
4.Data calculation
Bubble Sort.
//四、数据计算
//排序1:冒泡
for(int i=0;i<n-1;i++) {
for(int j=0;j<n-1-i;j++){
if(arr[j]>arr[j+1]){
int temp;
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
5. Output results
#include<iostream>
using namespace std;
int main(){
//一、分析问题
//已知:n个整数的数组
//未知:更新后的数组
//关系:从小到大进行排序-冒泡排序
//二、数据定义
int n,arr[10];
//三、数据输入
cin>>n;
for(int i=0;i<n;i++){
cin>>arr[i];
}
//四、数据计算
//排序1:冒泡
for(int i=0;i<n-1;i++) {
for(int j=0;j<n-1-i;j++){
if(arr[j]>arr[j+1]){
int temp;
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
//五、输出结果
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
return 0;
}