|
bubble sort- #include <stdio.h>
- #include <string.h>
- #define SWAP(a, b) {a ^= b; b ^= a; a ^= b;}
- /* xor swapping */
- int main()
- {
- char str[] = "clanguage";
- int i, j;
- int limit = strlen(str);
- for(i=0; i<limit; ++i){
- /* bubble sort每次都扫描未排序好的子序列,然后把最大值换到队尾去 */
- int changed = 0;
- /* 记录一次迭代中交换的次数 */
- for(j=0; j<limit-i-1; ++j)
- if(str[j] > str[j+1]){
- SWAP(str[j], str[j+1])
- changed += 1;
- /* 如果发现临近的两个值顺序颠倒就交换 */
- }
- if(changed == 0)
- break;
- /* 一次迭代中没有发现逆序对,说明已经排序好了 */
- }
- puts(str);
- return 0;
- }
复制代码 |
|