使用功能和指针的气泡分类
我有此功能代码可以使用指针对数组进行泡泡。
但是,我不明白第二个循环(内部循环):
他们为什么要p< a + n -i -1
?
void bubble_sort(int* a, int n) {
for (int i = 0; i < n; i++) {
for (int* p = a; p < a + n - i - 1; p++) { // bubble
if (*p > *(p+1)) {
int t = *p;
*p = *(p+1);
*(p+1) = t;
}
}
}
}
I have this function code to bubble sort an array using pointers.
However, I do not understand the second for loop (the inner one):
Why did they do p < a + n - i - 1
?
void bubble_sort(int* a, int n) {
for (int i = 0; i < n; i++) {
for (int* p = a; p < a + n - i - 1; p++) { // bubble
if (*p > *(p+1)) {
int t = *p;
*p = *(p+1);
*(p+1) = t;
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该比较
用于将数组的编辑部分绑定到阵列的未分类子数组。最后的
i
元素被排除在编辑之外,因为这些插槽将包含i
按顺序排序的数组的最大元素;因此,无需检查它们,并且可以避免这样做以防止功能浪费时间。减去1,以防止在i&gt; gt;时访问阵列的排序部分之外的元素。 0或在i = 0时,如果没有减去1时,则在i = 0时访问内存
,这可能会在p + 1被验证时可能会出现segfault。
The comparison
Is used to bound the edited portion of the array to the unsorted sub array of the array. The last
i
elements are excluded from being edited because these slots will consist of thei
greatest elements of the array in sorted order; therefore, there is no need to check them and doing so is avoided to prevent the function from wasting time.1 is subtracted to prevent the accessing of elements outside of the sorted portion of the array when i > 0 or to prevent the accessing of memory outside of the array when i = 0 by the line
If 1 was not subtracted, this would risk a SegFault when p + 1 is dereferenced.
因为您在下一行中比较
p
和p+1
:因此,如果您有n元素,则在最后一个元素之后
a+n
点。a+ni
点在子数组中的最后一个元素之后,但是在这种情况下,您将将最后一个元素与子数组中的最后一个元素进行比较。因此,您必须在最后一个元素之前停止:a+ni-1
Because you compare
p
andp+1
in the next line:So if you have n elements,
a+n
points after the last element.a+n-i
points after the last element in the sub array, but in this case you would compare the last element with the element after the last in the sub array. So you must stop before the last element thus:a+n-i-1