使用功能和指针的气泡分类

发布于 2025-01-28 20:42:18 字数 407 浏览 1 评论 0原文

我有此功能代码可以使用指针对数组进行泡泡。
但是,我不明白第二个循环(内部循环):
他们为什么要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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

回忆凄美了谁 2025-02-04 20:42:18

该比较

p < a + n - i - 1

用于将数组的编辑部分绑定到阵列的未分类子数组。最后的i元素被排除在编辑之外,因为这些插槽将包含i按顺序排序的数组的最大元素;因此,无需检查它们,并且可以避免这样做以防止功能浪费时间。

减去1,以防止在i&gt; gt;时访问阵列的排序部分之外的元素。 0或在i = 0时,如果没有减去1时,则在i = 0时访问内存

if (*p > *(p+1)) {

,这可能会在p + 1被验证时可能会出现segfault。

The comparison

p < a + n - i - 1

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 the i 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 (*p > *(p+1)) {

If 1 was not subtracted, this would risk a SegFault when p + 1 is dereferenced.

指尖上得阳光 2025-02-04 20:42:18

因为您在下一行中比较pp+1

         if (*p > *(p+1)) {

因此,如果您有n元素,则在最后一个元素之后a+n点。 a+ni点在子数组中的最后一个元素之后,但是在这种情况下,您将将最后一个元素与子数组中的最后一个元素进行比较。因此,您必须在最后一个元素之前停止:a+ni-1

        0                        n-i     n
array: [a-------------------------|------]
last inner:           p=a+n-i-1->||<-p+1

Because you compare p and p+1 in the next line:

         if (*p > *(p+1)) {

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

        0                        n-i     n
array: [a-------------------------|------]
last inner:           p=a+n-i-1->||<-p+1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文