程序算法基础知识
第一课 程序基础知识
1、算法的特性
2、算法的复杂度
#include<bits/stdc++.h>
using namespace std;
int sum(int n){
if(n==1){
return 1;
}
return sum(n-1)+n;
}
int main(){
cout<<sum(200);
return 0;
}
[GESP202409 三级] 平衡序列
#include<bits/stdc++.h>
using namespace std;
const int SIZE = 10005;
bool check(){
int x,arr[SIZE],sum=0,leftsum=0;
cin>>x;
for(int i=0;i<x;i++){
cin>>arr[i];
sum+=arr[i];
}
for(int i=0;i<x;i++){
leftsum+=arr[i];
if(sum - leftsum == leftsum){
return true;
}
}
return false;
}
int main(){
int n;
cin>>n;
while(n--){
cout<<(check()?"Yes":"No")<<endl;
}
return 0;
}
基础排序
常见算法复杂度与稳定性
冒泡排序
小的元素会经由交换慢慢“浮”到顶端,就像泡泡一样,故名“冒泡排序”。
它的工作原理是,重复地走访过要排序的元素,依次比较两个相邻的两个元素,如果前面的数比后面的数大就把他们交换过来。
走访元素的工作重复地进行,直到没有相邻元素需要交换
//冒泡排序
#include<bits/stdc++.h>
using namespace std;
const int SIZE = 10;
int arr[SIZE] = {2,7,8,4,36,78,1,91,42,13};
int main(){
for(int i = 0 ; i < SIZE - 1 ;i++){
for(int j = 0 ; j < SIZE - 1 - i ; j++){
if(arr[j] > arr[j+1])
swap(arr[j],arr[j+1]);
}
}
for(auto x : arr) cout<<x<<" ";
return 0;
}
选择排序
选择排序是第一个数字往后一个一个比较,再到第二个数字一个一个比较,以此类推。
//选择排序
#include<bits/stdc++.h>
using namespace std;
const int SIZE = 10;
int arr[SIZE] = {2,7,8,4,36,78,1,91,42,13};
int main(){
for(int i = 0 ; i < SIZE - 1 ;i++){
for(int j = i + 1;j < SIZE;j++){
if(arr[i] > arr[j]){
swap(arr[i],arr[j]);
}
}
}
for(auto x : arr) cout<<x<<" ";
return 0;
}