經典演算法學習——交換兩個整型資料_PHP教程

來源:互聯網
上載者:User

經典演算法學習——交換兩個整型資料


交換兩個數是在編程中經常會用到的,當然我們可以用很常見的方式來實現,也可以各種稀奇古怪的方法來做。這裡我們用三種比較常規的方式來做,太過古怪的方法個人覺得沒有太大必要。執行個體代碼上傳至:https://github.com/chenyufeng1991/SwapFunction

(1)使用指標

實現如下:

////  main.c//  SwapFunc////  Created by chenyufeng on 16/2/3.//  Copyright © 2016年 chenyufengweb. All rights reserved.//#include 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;}
(2)不借用第三個數
////  main.c//  SwapFunc////  Created by chenyufeng on 16/2/3.//  Copyright © 2016年 chenyufengweb. All rights reserved.//#include 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;}

(3)異或

////  main.c//  SwapFunc////  Created by chenyufeng on 16/2/3.//  Copyright © 2016年 chenyufengweb. All rights reserved.//#include /** *  由於我這裡用的是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;}
上面三種實現大家應該是應該閉著眼睛都能寫出來的,也是能夠完全理解的。

http://www.bkjia.com/PHPjc/1121831.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1121831.htmlTechArticle經典演算法學習——交換兩個整型資料 交換兩個數是在編程中經常會用到的,當然我們可以用很常見的方式來實現,也可以各種稀奇古怪的方...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.