冒泡排序C_整理

来源:互联网 发布:windows 10 to go教程 编辑:程序博客网 时间:2024/06/09 15:11

冒泡排序的原理

交换代码:

  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);}}}




原创粉丝点击