阿摩線上測驗 登入

申論題資訊

試卷:113年 - 113 經濟部所屬事業機構_新進職員甄試_資訊:1.資訊管理 2.程式設計#123421
科目:國營事業◆1.資訊管理 2.程式設計
年份:113年
排序:0

申論題內容

五、請實作下列函式以完成設計l個插入排序法(Insertion Sort),據以依參數值決定排序方式採遞增或遞減。(18分)
 bool isInverse(int x, int y, bool isAsc); //判斷傳入的x、y是否反序
  void InsertionSort(int *arr, int len, bool isAsc); //插入排序
(註:參數arr為傳入的整數陣列;參數len為整數陣列的長度;參數isAsc為是否遞增, 函式Insertion Sort應呼叫函式isInverse。)

詳解 (共 1 筆)

詳解 提供者:adamhsu622
// 這邊用 c 簡單驗證, 題目中的 bool 型態先用 int 型態替代
int isInverse(int x, int y, int isAsc) {
    // isAsc is true, 表示要遞增排序,但是 x > y, 故為 Inverse, 
   // 所以回傳 1,否則為 0
    if (isAsc == 1)
        return ((x > y) ? 1 : 0 );
 
    // isAsc is false,表示要遞減排序,但是 x < y, 故為 Inverse,
   // 所以回傳 1,否則為 0
    if (isAsc == 0)
        return ((x > y) ? 0 : 1 );
 
    return -1;
}
 
void InsertionSort(int *arr,int len, int isAsc) {
    int j,k,temp;
    
    for (int i = 2; i <=n; i++) { // 假設陣列索引值從 1 開始
        j = (i - 1), k = i;
            
        while (j > 0 && (isInverse(arr[j], arr[k], isAsc) == 1)) {
                temp = arr[k];
                arr[k] = arr[j];
                arr[j] = temp;
                j--;
                k--;
            }       
        }
    }
}
 
// 可用以下方式驗證
void main() {
    int arr[9] = {-1,2,5,1,19,100,21,-2,15};
    InsertionSort(arr,8,1);
    for (int i=1;i < 9;i++)
        printf("%d ",arr[i]);
}