Home > php教程 > php手册 > 经典算法学习交换两个整型数据

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

WBOY
Release: 2016-06-13 08:41:30
Original
1081 people have browsed it

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

交换两个数是在编程中经常会用到的,当然我们可以用很常见的方式来实现,也可以各种稀奇古怪的方法来做。这里我们用三种比较常规的方式来做,太过古怪的方法个人觉得没有太大必要。实例代码上传至: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>
Copy after login
(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>
Copy after login

(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>
Copy after login
上面三种实现大家应该是应该闭着眼睛都能写出来的,也是能够完全理解的。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template