每天一個小算法(1)----合並兩個已經排序的數組


《15道簡單算法題》伯樂在線的一篇文章,會接下來的一段時間每天花一點時間試着實現一個算法。

因為代碼比較簡單,故全部在main函數里實現,不會單獨另外寫一個函數,本代碼在linux/g++編譯運行正常。

今天是第一個:合並排序,將兩個已經排序的數組合並成一個數組,其中一個數組能容下兩個數組的所有元素;

基本思路:從后往前比較。

 1 #include <stdio.h>
 2 
 3 int main(int argc, char const *argv[])
 4 {
 5     const int aNum = 6;
 6     const int bNum = 8;
 7     int arrayIntA[aNum] = {5,9,14,23,33,56};
 8     int arrayIntB[aNum+bNum] = {6,7,15,17,20,25,30,57,0,0,0,0,0,0};
 9 
10     int iA = aNum - 1;
11     int iB = bNum - 1;
12     int iAB = aNum + bNum - 1;
13     while ( iA >= 0 && iB >= 0 && iAB >=0 )
14     {
15         if ( arrayIntA[iA] > arrayIntB[iB] )
16         {
17             arrayIntB[iAB] = arrayIntA[iA];
18             --iA;
19         }
20         else
21         {
22             arrayIntB[iAB] = arrayIntB[iB];
23             --iB;
24         }
25         --iAB;
26     }
27 
28     if ( iA < 0 )
29     {
30         while ( iAB >= 0 )
31         {
32             arrayIntB[iAB--] = arrayIntB[iB--];
33         }
34     }    
35 
36     if ( iB < 0 )
37     {
38         while ( iAB >= 0 )
39         {
40             arrayIntB[iAB--] = arrayIntA[iA--];
41         }
42     }
43 
44     for ( int i=0; i < aNum+bNum; ++i )
45     {
46         printf("%d ", arrayIntB[i]);
47     }
48     printf("\n");
49     return 0;
50 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM