Bubble sort array - program locking up

Hello,

Wondering if someone would take a look at this program and help me figure out why it's locking up when I compile it please? It is supposed to take the values and sort them using the bubble sort algorithm. It works fine if I don't use the "swap" function but that is a requirement for the question (as well as passing using pointers) and as soon as I put it in there, it locked up when I tried to compile. I'm not sure if I'm passing the data to it correctly maybe?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72

#include <iostream>
#include <cstdlib>

using namespace std;

int tmp;
int arr[] =  {56, 29, 12, 2, 83, 45, 96, 32, 6, 9};
int n = 10;
int counter = 0;
void bubbleSort (int *);
void swap (int *);


int main()
{
   cout << "Original Data: ";
   cout << endl;

   for (int i = 0; i < n; i++)
   {
      cout << arr[i] << " ";
   }

   cout << endl;
   cout << endl;

   cout << "Data items in ascending order: " << endl;

   bubbleSort(arr);

   for (int j = 0; j < n; j++)
   {
       cout << arr[j] << " " ;
   }

    cout << endl;
    cout << endl;
    cout << "Number of comparisons made " << counter << endl;
    cout << endl;

   return 0;
}


void bubbleSort(int arr[])
{
      int i;
      int q;

      for (q=0; q < n-1; q++)
      {
         for (i = 0; i < n-1; i++)
         {
            swap(arr);
         }
      }
}

void swap (int arr[])
{
    int i;
    if (arr[i] > arr[i+1])
    {
        tmp = arr[i];
        arr[i] = arr[i+1];
        arr[i+1] = tmp;
        counter++;
    }
}

Last edited on
The local variable 'i' in your swap function is never defined. Add to to the list of parameters to be passed from the bubbleSort function.
I'm not sure I understand. Do you mean put it in the swap function like so: swap(arr, i) and void swap (arr[], i)
Exactly. Right now you are looping i in your bubblesort function but swap has no idea about that so you have to give it the value every time. Add it as you suggested and remove int i; from line 62.
Changing it to that just gave me a page full of errors but......if I change it to swap (arr[i], i) and change the function to:

void swap (int *p1, int *p2)
{

if (*p1 > *p2)
{
int temp = *p1;
*p1 = *p2;
*p2 = temp;
counter++;
}
}

It runs but then gives me the wrong answer of 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
Number of comparisons made: 0
Last edited on
Got it figured out. Thanks for the suggestions. They finally helped me figure out what I needed to do to get it to run correctly. Now I just have to figure out how to optimize it.
Last edited on
Topic archived. No new replies allowed.