0

I have created a separate file to test my bubble sort algorithm for pset 3. The file compiles but when I run it, it just prints out the elements in the array in their original order! Can someone please help me understand why my algorithm is not sorting the array and swapping the elements as it should? My code is below:

#include <stdio.h>
#include <cs50.h>

void swap(int a, int b);
int main(void)
{
    int array[5] = {4, 2, 6, 3, 1};
    int swap_count = 2;
    int n = 5;
       for(int i = 0; i < n; i++)
       {
          if (swap_count != 0) 
          {
              for (int j = 0; j <= n-2; j++)
              {
                 swap_count = 0;
                 if(array[j] > array[j+1])
                 {
                   swap(array[j], array[j+1]);
                   swap_count++;
                 }
              }
          }
       }

printf("array[0] is:%i\n", array[0]);      
printf("array[1] is:%i\n", array[1]);
printf("array[2] is:%i\n", array[2]);
printf("array[3] is:%i\n", array[3]);
printf("array[4] is:%i\n", array[4]);
}

void swap(int a, int b)
{
    int* pa = &a;
    int* pb = &b;
    int temp = b;
    *pb = a;
    *pa = temp;
}
0

The swap() function takes two integers as parameters. Because parameters are passed by copy, the copied values are swapped in the function while the original values remain unaffected in main. So, nothing happens in the list. However, if the function took the address of the values as parameters, it would work. Perhaps a review of the lectures and shorts on functions would be in order?

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

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