插入排序算法

时间:2018-03-09 17:14:55

标签: c algorithm sorting insertion-sort

我正在阅读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.
 }
}

1 个答案:

答案 0 :(得分:1)

您没有调用insertionSort函数。只需添加:

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");

让它适合我。

请注意,您必须为stdlib.h添加calloc