[英]Insertion Sort Algorithm
I am reading Cormen Introduction To Algorithms book and i'm trying to translate the pseudocode of Insertion Sort example into real C code. 我正在阅读《 Cormen 算法入门》一书,并试图将“ 插入排序”示例的伪代码转换为真实的C代码。
The problem is that the algorithm i wrote seems not working and i cannot understand why; 问题是我写的算法似乎不起作用,我不明白为什么。 for instance when i insert something like: {4, 3, 2, 1}
the output still be the same and when i insert something like {8, 9, 1, 12, 3}
the output become {8, 9, 1, 12, 3}
which doesn't make any sense. 例如,当我插入诸如{4, 3, 2, 1}
之类的内容时,输出仍然是相同的;当我插入诸如{8, 9, 1, 12, 3}
之类的内容时,输出变为{8, 9, 1, 12, 3}
这没有任何意义。
Someone can find what i did wrong? 有人可以找到我做错了吗?
This is the code i wrote: 这是我写的代码:
#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.
}
}
You are not calling the insertionSort
function. 您没有在调用insertionSort
函数。 Just adding: 只需添加:
for (int i = 0; i < size; i++) {
printf("Insert the %d element: ", i+1);
scanf_s("%d", &Arr[i]);
}
insertionSort(Arr, size);
//Print the result
printf("Sorted array: \n");
Made it work for me. 使它对我有用。
Note that you alse have to include stdlib.h
for calloc
. 请注意,您还必须为calloc
包括stdlib.h
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.