C++学习--常用的几种算法
冒泡排序法:
vector<int> bubbleSort(vector<int>& nums) {
int N = nums.size();
for (int i = 0; i < N - 1; i++) {
for (int j = 0; j < N - 1 - i; j++) {
if (nums[j] > nums[j + 1]) {
swap(nums[j], nums[j + 1]);
}
}
}
return nums;
}
int main() {
int tmp[]={0,2,1,41,32,56,3,56,90,10};
std::vector<int> buf(tmp,tmp+10);
vector <int> nums;
nums=bubbleSort(buf);
for(int a: nums)
{
cout<<a<<endl;
}
}
执行完成,耗时:0 ms 0 1 2 3 10 32 41 56 56 90
递归算法: 指数 O(2N)O(2^N)O(2N) :
生物学科中的 “细胞分裂” 即是指数级增长。初始状态为 111 个细胞,分裂一轮后为 222 个,分裂两轮后为 444 个,……,分裂 NNN 轮后有 2N2^N2N 个细胞。
算法中,指数阶常出现于递归,算法原理图与代码如下所示。
int algorithm(int N) { if(N<=0) return 1; int count_1=algorithm(N-1); int count_2=algorithm(N-1); return count_1+count_2; } int main() { int result=algorithm(16); cout<<result<<endl; }
执行完成,耗时:0 ms 65536

浙公网安备 33010602011771号