國立暨南國際大學 101 學年度第一學期小考試卷

科目名稱:計算機概 論 開課系所:資訊工程 學系 考試日期 2012.12.28
系所別:
年級:
學號:
姓名:
考試時間 08:10-08:20

  1. (10%) Determine whether the following code is correct or not.  If it is correct, predict its output.  If it is incorrect, point out the mistake(s).
    // Bubble Sort
    #include <iostream>

    int bsort1(int A[], int n)
    {
        int i,j,temp;
        bool sorted;
        for (i=n-1; i>0 ; i--)
        {
            sorted = true;
            for (j=0 ; j<i ; j++)       
                if (A[j] > A[j+1])
                {
                    temp = A[j]; A[j] = A[j+1]; A[j+1] = temp;
                    sorted = false;
                }       
            if (sorted)
                return n-i;
        }
        return n-1;
    }

    int main()
    {
        int a[] = { 8, 1, 3, 2, 5, 4, 6, 7 };   
        int size = sizeof(a) / sizeof(a[0]);
        int n = 0;
        n = bsort1(a, size);
        std::cout << "It takes " << n << " pass"
            << (n>1?"es":"") << " to sort the sequence.\n";   
        return 0;
    }


  2. (10%) Determine whether the following code is correct or not.  If it is correct, predict its output.  If it is incorrect, point out the mistake(s).
    // Array of Pointers to Functions
    #include <iostream>
    void print_array(int a[], int n)
    {
            for (int i=0; i<n; i++)
                std::cout << a[i] << ' ';
            std::cout << '\n';
    }

    int cmp1(int a, int b)
    {
        if (a < b)       
            return -1;       
        else
            if (a == b)
                return 0;
            else
                return 1;
    }
    int cmp2(int a, int b)
    {
        if (a > b)       
            return -1;       
        else
            if (a == b)
                return 0;
            else
                return 1;
    }

    int bsort(int a[], int n, int (*pfun)(int a, int b) )
    {
            int i, j, temp;
            for (i=n-1; i>=1; i--)
                for (j=0; j<i; j++)
                    if (pfun(a[j] , a[j+1]) > 0 )
                    {
                        temp = a[j];
                        a[j] = a[j+1];
                        a[j+1] = temp;
                    }
            return 0;
    }

    int main()
    {
            int a[] = { 7, 3, 5, 1, 6, 4, 2 };
            int size = sizeof(a) / sizeof(a[0]);
           
            int (*pfun[2])(int, int) = { cmp1, cmp2 };
            for (int i=1; i>=0; i--)
            {
                bsort(a, size, *(pfun+i));   
                print_array(a, size);
            }
            return 0;
    }