冒泡排序的原理
交换代码:
- 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); } } }
- {
- int c;
- c = *a;
- *a = *b;
- *b = c;
- }
思路都了解,下面的算法仅供参考。
简单算法:两个for循环,都执行n次
复杂度 :n的平方
核心代码:
- int out, in, min;
- for (out = 0; out < total; out++){
- min = num[out];
- for (in = 0; in < total; in++){
- if(min > num[in]){
- swap(&min, &num[in]);
- }
- }
- }
复杂度:约为n的平方
核心代码:
- int out, in;
- for (out = 0; out < total; out++){
- for (in = total-1; in > out; in--){
- if(num[in] > num[in-1]){
- swap(&num[in], &num[in-1]);
- }
- }
- }
针对执行此时:执行方向优化
核心代码:
- int out,in;
- for (out = total - 1; out > 1; out--){
- for (in = 0; in < out; in++){
- if(num[in] < num[in-1]){
- swap(&num[in],&num[in+1]));
- }
- }
- }
针对内存占用减少:添加一个flag
复杂度:最好为n,最差,flag失效。
核心代码:
- int out, in, flag = 1;
- for (out = 0; out < total && flag; out++){
- flag = 0;
- for (in = total-1; in > out; in--){
- if(num[in] > num[in-1]){
- swap(&num[in], &um[in-1]);
- flag = 1;
- }
- }
- }
针对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);
}
}
}