gpt4 book ai didi

c - 插入排序算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:10:57 25 4
gpt4 key购买 nike

我正在阅读 Cormen Introduction To Algorithms 一书,我正在尝试将 Insertion Sort 示例的伪代码转换为真正的 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.
}
}

最佳答案

您没有调用 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");

让它对我有用。

请注意,您还必须为 calloc 包含 stdlib.h

关于c - 插入排序算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49198885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com