求數組逆置(數組與指針實現)


數組逆置

  基本思路:

  將a[0]與a[n-1]對換,再將a[1]與a[n-2]對換…直到將a[int(n-1)]與a[int((n-1)/2)-1]對換。

  如圖所示:


  使用數組來實現:


  1. //數組實現逆置
    void conver_arr(int c,int a[])
    {
        int low =0;
        int high = c -1;
        for(int i =0; i < c/2; i++)
        {
            if(low < high)
            {
                int temp = a[c - i -1];
               a[c - i -1]= a[i];
                a[i]= temp;
            }
        }
    }

     


  使用指針來實現:

  1. //指針實現逆置
    void conver_point(int c,int*a)
    {
        int*start;
        start = a;
        int*end;
        end= a + c -1;
        while(start <end)
        {
            int*temp =*start;
            *start =*end;
            *end= temp;
            *start++;
            *end--;
        }
    }

     


  其他代碼:

  1. //打印輸出信息
    void arr_print(int*a)
    {
        for(int i =0; i <10; i++)
        {
            printf("a[%d] = %d\n", i+1, a[i]);
        }
    }
    int main(void)
    {
        int arr_value[10]={12,34,5,67,3,54,6,31,46,1};
        int len =sizeof(arr_value)/sizeof(arr_value[0]);
        conver_arr(len, arr_value);
        conver_point(len, arr_value);
        arr_print(arr_value);
        return0;
    }

     


  運行結果如下圖所示:

 


免責聲明!

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



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