1

A am trying an implementation of some sorting algorithms and I have to calculate how much time they spend. This is the function I wrote:

void bubble_sort(int A[], int len) {
bool ord = false;
    for (int i=0; i<len-1 && ord==false; i++) {
        ord = true;
        for (int j=len-1; j>i; j--) {
            if (A[j]-1>A[j]) {
                ord = false;
                swap(A[j]-1, A[j]);
            }
        }
    }
}

And of course here there is a typical swap() function:

void swap(int x, int y) {
    int d;
    d = x;
    x = y;
    y = d;
}

I am not having troubles with Insertion Sort, Selection Sort and Merge Sort. By the way bubble_sort is not sorting the numbers in my array.

I cannot find what's wrong. Do you have any ideas?

3
  • change to void swap(int a[], int x, int y); Commented Jan 12, 2014 at 22:56
  • In order to replace the entity. Commented Jan 12, 2014 at 22:59
  • 1
    there are several possible fixes, but as said by others, your swap is wrong. Commented Jan 12, 2014 at 23:09

2 Answers 2

3

In C, function parameters are passed by value, not by reference. your swap() function does nothing (it doesn't even return... didn't your compiler complain?)

To actually sort, you have to change swap() to

void swap(int *x, int *y) {
    int d = *x;
    *x = *y;
    *y = d;
    return;
}

and invoke it with

swap(&A[j-1], &A[j]);
Sign up to request clarification or add additional context in comments.

2 Comments

I use wxDevC++ and it doesn't complain.
@EOF Your function is wrong. Read your the firs sentence of your own answer to fix it. Also your don't have to return a void function.
1

You have to include -1 in array A. Not outside the []. Your code non just chech if value in A[j]minus 1 is bigger than value in A[j]. Which is obviously always false.

Also in swap function you dont pass the ponter of the Array A. Actually swap() does nothing.

Try

if (A[j-1]>A[j]) {
                ord = false;
              int temp=A[j-1];
           A[j-1]=A[j];
           A[j]=temp;

2 Comments

Your code works, going to accept it. I have also removed the swap function
@AlbertoRossi yes you remove swap and also declare int temp outside the loop for a cleaner code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.