[英]Insertion Sort C programming
Since this year I'm starting studying C programming at university.从今年开始,我开始在大学学习 C 编程。 In particular today I was trying to understand the insertion sort.特别是今天我试图理解插入排序。 I wrote this code that is perfectly working:我编写了这段完美运行的代码:
void insertionSort (int v[], int s)
{
int i;
int j;
int value;
for (i = 1; i < s; i++)
{
value = v[i];
for (j = i - 1; (j >= 0) && (value < v[j]); j --)
{
v[j + 1] = v[j];
}
v[j + 1] = value; // why v[j+1]?
}
}
My question is about the last code line: v[j + 1] = value
.我的问题是关于最后一行代码: v[j + 1] = value
。 If I understand correctly, j
(that decreases every time), at the end of the for
cycle, has a value of -1 and that's why is correct to write v[j + 1] = value
.如果我理解正确, j
(每次都会减小)在for
循环结束时的值为 -1,这就是为什么写v[j + 1] = value
是正确的。 Am I right or am I missing something?我是对的还是我错过了什么? Really thanks for anybody who wants to help me by explaining me better.真的感谢任何想通过更好地解释我来帮助我的人。
The way you have your code setup right now, you need v[j + 1] because j will always be one before where you want to insert. 现在,您设置代码的方式需要v [j + 1],因为j始终是您要插入的位置之前的1。
For example: 例如:
int v[6] = {1, 34, 2, 50, 4, 10} int v [6] = {1、34、2、50、4、10}
s = sizeof(v) / sizeof(v[0]) = 6 s = sizeof(v)/ sizeof(v [0])= 6
Stepping through your code: 逐步执行代码:
Looking at your array, it looks like this: 1, 34, 34 看一下数组,它看起来像这样:1,34,34
So again, the significance of v[j + 1] is to insert in the correct place. 同样,v [j + 1]的意义在于将其插入正确的位置。 If the value is already in the correct place than you swap with itself. 如果该值已经在正确的位置,则您将与其自身交换。
Over here you can find an visualized example: https://visualgo.net/en/sorting 在这里,您可以找到一个可视化的示例: https : //visualgo.net/en/sorting
Here you have an example in C: 这里有一个C语言示例:
#include <stdio.h>
int main()
{
int n, array[1000], c, d, t;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++) {
scanf("%d", &array[c]);
}
// Insertion Sort
for (c = 1 ; c <= n - 1; c++) {
d = c;
while ( d > 0 && array[d] < array[d-1]) {
t = array[d];
array[d] = array[d-1];
array[d-1] = t;
d--;
}
}
printf("Sorted list in ascending order:\n");
for (c = 0; c <= n - 1; c++) {
printf("%d\n", array[c]);
}
return 0;
}
mark first element as sorted 将第一个元素标记为已排序
for each unsorted element 对于每个未分类的元素
'extract' the element “提取”元素
for i = lastSortedIndex to 0 对于i = lastSortedIndex为0
if currentSortedElement > extractedElement 如果currentSortedElement> extractElement
move sorted element to the right by 1 将排序的元素向右移动1
else: insert extracted element 其他:插入提取的元素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.