五、請實作下列函式以完成設計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。)
申論題作答 (共 3 筆)
依時間顯示最近 3 筆。
哈哈
申論題作答 #105651
93 分
93
總分
63分8秒 總時間
1 人解鎖
2026.09
正文
include<iostream using namespace std; bool isInverse(int x, int y, bool...
Fuuuuuuuu
申論題作答 #93987
75 分
75
總分
1分56秒 總時間
5 人解鎖
2026.07
正文
C++ // 1. 判斷x與y之間的順序 // isAsc == true,代表x與y之間需要漸增 // i...
Fuuuuuuuu
申論題作答 #91768
36 分
36
總分
3分5秒 總時間
2 人解鎖
2026.07
正文
cpp bool isInverse(int x, int y, bool isAsc) { // 狀況一:若要求遞增排序...
詳解 (共 3 筆)
t23
詳解 #6848839
#include <stdio.h...
(共 1095 字,隱藏中)
前往觀看
佳佳
詳解 #6234987
使用C++實作如下: #include...
(共 1159 字,隱藏中)
前往觀看
adamhsu622
詳解 #6235556
// 這邊用 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 );
return ((x > y) ? 1 : 0 );
ㅤㅤ
// isAsc is false,表示要遞減排序,但是 x < y, 故為 Inverse,
// 所以回傳 1,否則為 0
if (isAsc == 0)
return ((x > y) ? 0 : 1 );
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--;
}
}
}
}
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};
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]);
}
for (int i=1;i < 9;i++)
printf("%d ",arr[i]);
}