简体   繁体   English

冒泡排序C程序中可能的错误

[英]Possible mistake in bubble sort c program

I was reading the book "Computer Organization and Design" by Patterson and Hennesy (5th Edition) and found this bubble sort code: 我正在阅读Patterson和Hennesy(第5版)的书“计算机组织和设计”,发现此冒泡排序代码:

void sort (int v[], int n)
{
    int i,j;
    for (i=0; i<n; i+=1) {
        for (j = i-1; j>=0 && v[j] > v[j+1]; j+=1) {
            swap(v,j);
        }
    }
}

void swap (int v[], int k) {
    int temp;
    temp = v[k];
    v[k] = v[k+1];
    v[k+1] = temp;
}

I don't understand how this function would sort an array. 我不明白该函数将如何对数组进行排序。 Especially if the first element of the array is also the largest, it seems to me that the index j would go out of bounds. 特别是如果数组的第一个元素也是最大的,在我看来,索引j会超出范围。 Running the code and printing the indices confirmed this. 运行代码并打印索引确认了这一点。

This is the code I used: 这是我使用的代码:

#include <stdio.h>

void swap (int v[], int k) {
    int temp;
    temp = v[k];
    v[k] = v[k+1];
    v[k+1] = temp;
}

void sort (int v[], int n)
{
    int i,j;
    for (i=0; i<n; i+=1) {
        printf("%d \n", i);
        for (j = i-1; j>=0 && v[j] > v[j+1]; j+=1) {
            printf("%d, %d \n", i, j);
            swap(v,j);
        }
    }
}

int main() {
    int x[3] = {5,1,2};
    int N = 3;

    sort(x, N);
    for(int i = 0; i < 3; i++) {
        printf("%d ", x[i]);
    }
    return 0;
}

This was the result: 结果是:

/Users/mauritsdescamps/Desktop/test/cmake-build-debug/test
0 
1 
1, 0 
1, 1 
1, 2 
1, 3 
1, 4 
2 
2, 1 
2, 2 
2, 3 

Process finished with exit code 6

Is there something I am forgetting? 有什么我忘记的事情吗? If not, I think there must be a mistake in the second loop condition. 如果没有,我认为第二个循环条件一定有一个错误。 I have seen other implementations of the algorithm but I want to know how to get this approach to work. 我已经看到了该算法的其他实现,但是我想知道如何使这种方法起作用。

I've tried this code, too. 我也尝试过此代码。 I have compiled it with GCC and somehow it worked for me (the exit status of the program was 0 and the array was sorted correctly). 我已经用GCC对其进行了编译,并且以某种方式对我有用(程序的退出状态为0,数组已正确排序)。 But I also think that their is a problem with the second loop. 但是我也认为第二循环是一个问题。 I would change the j+= 1 instruction into j-=1. 我会将j + = 1指令更改为j- = 1。 Otherwise the second loop could end in an infinite loop. 否则,第二个循环可能以无限循环结束。 Additionally I would change the i=0 instruction in the first loop into ai=1 instruction, because it would end in an unnecessary iteration. 另外,我会将第一个循环中的i = 0指令更改为ai = 1指令,因为它将以不必要的迭代结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM