1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| void selection_sort_teaching_demo(int arr[], int n) { printf("=== 选择排序教学演示 ===\n"); printf("数组大小: %d\n", n); printf("\n初始状态:\n"); for (int i = 0; i < n; i++) { printf("[%2d] ", arr[i]); } printf("\n"); for (int i = 0; i < n; i++) { printf(" %2d ", i); } printf("\n\n"); for (int i = 0; i < n - 1; i++) { printf("--- 第 %d 轮 ---\n", i + 1); printf("在位置 %d 到 %d 中寻找最小值...\n", i, n - 1); int min_index = i; int min_value = arr[i]; for (int j = i + 1; j < n; j++) { printf("比较 arr[%d]=%d 和 当前最小值 %d: ", j, arr[j], min_value); if (arr[j] < min_value) { min_index = j; min_value = arr[j]; printf("找到新的最小值 %d\n", min_value); } else { printf("保持当前最小值\n"); } } printf("最小值 %d 位于索引 %d\n", min_value, min_index); if (min_index != i) { printf("交换 arr[%d]=%d 和 arr[%d]=%d\n", i, arr[i], min_index, arr[min_index]); swap(&arr[i], &arr[min_index]); } else { printf("最小值已在正确位置,无需交换\n"); } printf("第 %d 轮结果: ", i + 1); for (int k = 0; k < n; k++) { if (k <= i) { printf("[%2d] ", arr[k]); } else { printf(" %2d ", arr[k]); } } printf("\n\n"); } printf("最终排序结果: "); for (int i = 0; i < n; i++) { printf("[%2d] ", arr[i]); } printf("\n"); }
void test_teaching_demo() { printf("=== 教学演示测试 ===\n"); int arr[] = {64, 25, 12, 22, 11}; int n = sizeof(arr) / sizeof(arr[0]); selection_sort_teaching_demo(arr, n); printf("\n"); }
|