【发布时间】:2018-03-09 17:14:55
【问题描述】:
我正在阅读 Cormen 算法简介一书,我正在尝试将 插入排序 示例的伪代码翻译成真正的 C 代码。
问题是我写的算法似乎不起作用,我不明白为什么;例如,当我插入类似{4, 3, 2, 1} 的内容时,输出仍然相同,而当我插入类似{8, 9, 1, 12, 3} 的内容时,输出变为{8, 9, 1, 12, 3},这没有任何意义。
有人能找出我做错了什么吗?
这是我写的代码:
#include <stdio.h>
void insertionSort(int *Arr, unsigned int size);
int main(void) {
//The size of the array
unsigned int size = 0;
printf("Insert how many elements you want to sort(min 2): ");
scanf_s("%d", &size);
//Check if the value are higher than 1
while (size < 2) {
printf("\nPlease, choose a higher value: ");
scanf_s("%d", &size);
}
//Let's define the array with the choosen size
//The array is allocated dynamically on the heap of the memory
int *Arr;
Arr = calloc(size, sizeof(int));
//Ask the elements
printf("Insert %d elements:\n", size);
for (int i = 0; i < size; i++) {
printf("Insert the %d element: ", i+1);
scanf_s("%d", &Arr[i]);
}
//Print the result
printf("Sorted array: \n");
for (int i = 0; i < size; i++)
printf("%d\n", Arr[i]);
free(Arr);
return 0;
}
void insertionSort(int *Arr, unsigned int size) {
for (int j = 1; j < size; j++) { //Start with the 2nd element of the array
int key = Arr[j]; //the current element of A[j] is stored in key
int i = j;
while ((i >= 1) && (Arr[i - 1] > key)) {
Arr[i] = Arr[i - 1];
i--;
}
Arr[i] = key; //at position I(decreased by 1) is stored Key.
}
}
【问题讨论】:
-
单行
Arr[i] = Arr[i - 1];在我看来不像是交换,这就是插入排序所做的。
标签: c algorithm sorting insertion-sort