0

I made a bubble sort code, but I want to make sure that my code is correct. My code is

void sort(int values[], int n)
{
    if (n == 1) {
        return 0;
    } 
        int swapcount = 0;
        for (int j = 0; j < n - 1; j++) {

            int compare1 = values[i];
            int compare2 = values[i + 1];

            if (compare1 > compare2) {
                swap(compare1, compare2);
                i++;
                swapcount++;
            }

            else {
                i++;
            }
        }
        if (swapcount == 0) {
            return 0;
        }
    void sort(int values[], int n);
    // TODO: implement a sorting algorithm
    return;
}

void swap(compare1, compare2) {
    int placeholder;

    placeholder = compare2;
    compare2 = compare1;
    compare1 = placeholder;

}

1 Answer 1

0

The most serious error is that your swap function does not really swap any value, because you are passing the variables by value instead of by reference, it is also necessary to declare the types of variables in the definition of a function thing that you do not do in swap. You also try to exchange the compare variables, to which you assign values [i], you are not going to change values [i] in fact. As for sort will tell you that you declare it as void, then you can not return any value, however you have statements return 0, which is incorrect. It's worth it that you look at the theory again, and do not complicate the code unnecessarily, the algorithms of sorting are difficult, I think it is enough to understand them, I advise you not to use more functions, you can use a test program with a function main to test your code.

2
  • If that doesn't actually swap two number, How do I go about doing that? Also, thanks for your input, I will be sure to revise and make changes
    – Joel Banks
    Commented Jul 5, 2017 at 0:33
  • Swap is fine, but without using functions, if we use a swapping function we must use pointers
    – MARS
    Commented Jul 5, 2017 at 17:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .