冒泡排序C_整理

冒泡排序的原理

交换代码:

  1. void swap(int *a, int *b)  
    for (i_cnt = 0; i_cnt < WIFIAP_CNT; i_cnt++){
            for (j_cnt = WIFIAP_CNT-1; j_cnt < i_cnt; j_cnt--){
                if (resp->stWifiAp[j_cnt].signal > resp->stWifiAp[j_cnt-1].signal){
                    swap_ap(&resp->stWifiAp[j_cnt], &resp->stWifiAp[j_cnt-1]);
                }
    			if (strcmp(resp->stWifiAp[j_cnt].ssid, stWifiAp_singal_max->ssid) == 0){
    				//swap_ap(&resp->stWifiAp[j_cnt], &resp->stWifiAp[devicecount-1]);
    				devicecount --;
    				resp->stWifiAp[j_cnt].signal = 0;
    				printf("ssid: %s, cnt: %d\n", resp->stWifiAp[j_cnt].ssid, j_cnt);
    			}
            }
        }

  2. {  
  3.     int c;  
  4.      c = *a;  
  5.     *a = *b;  
  6.     *b =  c;  
  7. }  

思路都了解,下面的算法仅供参考。

简单算法:两个for循环,都执行n次

复杂度 :n的平方

核心代码:

  1. int out, in, min;  
  2. for (out = 0; out < total; out++){
  3.   min = num[out];  
  4.   for (in = 0; in < total; in++){  
  5.     if(min > num[in]){  
  6.        swap(&min, &num[in]);
  7.     }  
  8.   }  
  9. }  
优化for循环次数:第二for循环以第一for循环为基础

复杂度:约为n的平方

核心代码:

  1. int out, in;  
  2. for (out = 0; out < total; out++){
  3.  for (in = total-1; in > out; in--){  
  4.    if(num[in] > num[in-1]){  
  5.       swap(&num[in], &num[in-1]);
  6.   }  
  7.  }  

针对执行此时:执行方向优化

核心代码:

  1. int out,in;  
  2. for (out = total - 1; out > 1; out--){  
  3.  for (in = 0; in < out; in++){  
  4.    if(num[in] < num[in-1]){
  5.      swap(&num[in],&num[in+1]));  
  6.    }  
  7.  }  
  8. }  

针对内存占用减少:添加一个flag

复杂度:最好为n,最差,flag失效。

核心代码:

  1. int out, in, flag = 1;  
  2. for (out = 0; out < total && flag; out++){
  3.   flag = 0;
  4.   for (in = total-1; in > out; in--){  
  5.     if(num[in] > num[in-1]){  
  6.        swap(&num[in], &um[in-1]);
  7.        flag = 1;
  8.     }  
  9.   }  
针对wifi获取列表信息,信号强弱排序,删除重复网络ssid
for (i_cnt = 0; i_cnt < WIFIAP_CNT; i_cnt++){
	for (j_cnt = WIFIAP_CNT-1; j_cnt < i_cnt; j_cnt--){
		if (resp->stWifiAp[j_cnt].signal > resp->stWifiAp[j_cnt-1].signal){
			swap_ap(&resp->stWifiAp[j_cnt], &resp->stWifiAp[j_cnt-1]);
		}
		if (strcmp(resp->stWifiAp[j_cnt].ssid, stWifiAp_singal_max->ssid) == 0){
			//swap_ap(&resp->stWifiAp[j_cnt], &resp->stWifiAp[devicecount-1]);
			devicecount --;
			resp->stWifiAp[j_cnt].signal = 0;
			printf("ssid: %s, cnt: %d\n", resp->stWifiAp[j_cnt].ssid, j_cnt);
		}
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值