Data Structures and Algorithms (II) - the time complexity of the algorithm

A. Algorithm time complexity

1. recursive accumulation i ~ j:

#include<stdio.h>
int fun(int k,int n){
    if(n<=k){        //最后一个数 
        return k;    //函数出口 
    } 
    else{
        return fun(k,n-1)+n;  //递归累加,将本次的n与n-1相加并继续计算
    }
    
}
int main(){
    int result = fun(1,100);
    printf("%d",result);
    return 0;
}

operation result:

return fun (k, n-1) + n; the frequency of execution of the statement is T (n).

Time complexity is O (N), the program returns as fun this function is added to the current from the n-n forward decrease until n <n at k = k plus returns the final result obtained.

2. Optimize the time complexity

C implemented using binary sort:

#include<stdio.h>

int a[101],n;
void quick_sort(int left,int right) {
	int i , j, temp ,t;
	if(left > right){
		return;
	}
	temp = a[left];		//以第一个数为基准
	i = left;
	j = right;
	while(i!=j){
		while(a[j]>=temp && i<j){	//从后往前与temp比较 
			j--;			//temp比不过a[j],前移一位继续与temp比较 
		}
		while(a[i]<=temp && i<j){	//从前往后与temp比较 
			i++;			//temp比a[i]大则与后一位继续比较 
		}
		if(i<j){	//直到不满足以上条件了 
			//交换数组
			t = a[i];
			a[i] = a[j];
			a[j] = t; 
		} 
	}
	a[left] = a[i];	//将交换的这一个数组重新指定为临时变量
	a[i] = temp;	//将一开始的临时变量放到该位置 
    //以交换的位置为界分开处理,继续二分处理 
	quick_sort(left,i-1);   
	quick_sort(i+1,right);
	return ;
}

int main(){
	int i;
	printf("输入总共多少个数据:\n");
	scanf("%d",&n);
	printf("输入准备排序的数据:\n"); 
	for( i = 1;i <= n; i++){
		scanf("%d",&a[i]);
	}
	quick_sort(1,n);
	printf("快速排序后的数据:\n"); 
	for( i = 1;i <= n; i++){
		printf("%d ",a[i]);
	}
}

Using dichotomy is possible to reduce the number of times of execution of the code to optimize the time complexity, the number of computations is: the ASL = {[(n-+. 1) / n-] Iog2 ^ * (n-+. 1)} -. 1 , so the time complexity of the program degree of O (log2N).

Run the structure of its program as a tree structure:

3. The worst time complexity.

Bubble implement sorting:

#include <stdio.h>
 
int main(){
	int a[10];
	int i,j,temp=0;
	printf("输入准备排序的数字:");
	for(i = 0;i<10;i++){
		scanf("%d",&a[i]);
	}
	for(i=0;i<9;i++){	//从a[0]开始与其他数组比较 
		for(j=0;j<10-i;j++){		// 排好的数组放在n-i位的后一位,所以不需要与这些数组比较 
			if(a[j+1]<a[j]){	//从小到大排序
				temp=a[j];
				a[j]=a[j+1];
				a[j+1]=temp;
			}
		}	
	}
	for(i=0;i<10;i++){
		printf("%3d",a[i]);
	} 
	return 0;
}

operation result:

From time to read out the operation time of 3.999s, the time complexity of the algorithm is the worst case i.e. n * n (n ^ 2).

Published 58 original articles · won praise 31 · views 40000 +

Guess you like

Origin blog.csdn.net/qq_37504771/article/details/104255161