ホームページ  >  記事  >  php教程  >  经典算法学习交换两个整型数据

经典算法学习交换两个整型数据

WBOY
WBOYオリジナル
2016-06-13 08:41:301021ブラウズ

经典算法学习——交换两个整型数据

交换两个数是在编程中经常会用到的,当然我们可以用很常见的方式来实现,也可以各种稀奇古怪的方法来做。这里我们用三种比较常规的方式来做,太过古怪的方法个人觉得没有太大必要。实例代码上传至:https://github.com/chenyufeng1991/SwapFunction

(1)使用指针

实现如下:

//
//  main.c
//  SwapFunc
//
//  Created by chenyufeng on 16/2/3.
//  Copyright © 2016年 chenyufengweb. All rights reserved.
//

#include <stdio.h>

void swap01(int *a,int *b);

int main(int argc, const char * argv[]) {

    int a = 1;
    int b = 2;
    printf("交换前:a = %d,b = %d\n",a,b);
    swap01(&a, &b);
    printf("交换后:a = %d,b = %d\n",a,b);

    return 0;
}

//最常规的交换;
void swap01(int *a,int *b){

    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}
</stdio.h>
(2)不借用第三个数
//
//  main.c
//  SwapFunc
//
//  Created by chenyufeng on 16/2/3.
//  Copyright &copy; 2016年 chenyufengweb. All rights reserved.
//

#include <stdio.h>

void swap02(int *a,int *b);

int main(int argc, const char * argv[]) {

    int a = 1;
    int b = 2;
    printf("交换前:a = %d,b = %d\n",a,b);
    swap02(&a, &b);
    printf("交换后:a = %d,b = %d\n",a,b);

    return 0;
}

//不用第三个数;
void swap02(int *a,int *b){

    *a = *a + *b;
    *b = *a - *b;
    *a = *a - *b;
}
</stdio.h>

(3)异或

//
//  main.c
//  SwapFunc
//
//  Created by chenyufeng on 16/2/3.
//  Copyright &copy; 2016年 chenyufengweb. All rights reserved.
//

#include <stdio.h>

/**
 *  由于我这里用的是C语言,所以不能使用引用。C++中可以使用引用。
 引用的函数定义:
 void swap04(int &a,int &b){
 ...
 }
 */

void swap03(int *a,int *b);

int main(int argc, const char * argv[]) {

    int a = 1;
    int b = 2;
    printf("交换前:a = %d,b = %d\n",a,b);
    swap03(&a, &b);
    printf("交换后:a = %d,b = %d\n",a,b);

    return 0;
}

//异或,使用二进制位进行计算;
void swap03(int *a,int *b){

    *a = *a ^ *b;
    *b = *b ^ *a;
    *a = *a ^ *b;
}
</stdio.h>
上面三种实现大家应该是应该闭着眼睛都能写出来的,也是能够完全理解的。
声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。