Bubble sort function causing trouble

I wrote a small program in which I use a bubble sort function to sort the strings in an array in ascending order. The bubble sort function I wrote is causing both trouble and some confusion. The function works fine as long as c > 0 but causes the program to crash as soon as c = 0 (meaning there are no words to sort in the string array). I simply can't seem to figure out why this is so any help would be greatly appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
string* sort(string* sA, size_t c)
{
	bool swapped = false;	

	while(true)	
	{
		for(size_t i = 0; i < (c - 1); i++)
		{
			if(sA[i] > sA[i+1])			
			{
				sA[i].swap(sA[i+1]);
				swapped = true;			
			}
		}

		if(!swapped)					
			break;

		swapped = false;					
	}
	return sA;
}
I think it is caused by your for loop condition check for(size_t i = 0; i < (c - 1); i++). I think it will evaluate to i< -1 condition. Check for the c = 0 inside the while, before for loop.
closed account (28poGNh0)
You're using a pointer(string* sA) points probably to strings you want to order so why you need to return from sort function?

another version

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
# include <iostream>
using namespace std;

void sort(string *sA,size_t strSize)
{
	for(size_t i = 0; i < strSize-1; i++)
	{
	    for(size_t j = i; j < strSize; j++)
        {
            if(sA[i] > sA[j])
			{
				sA[i].swap(sA[j]);
			}

        }
	}
}

int main()
{
    string str[] = {"I","wrote","a","small","program","i","which","I","use","a","bubble","sort",
                    "function","to","sort","","strings","in","an","array","in","ascending","order"};

    size_t strSize = sizeof(str)/sizeof(*str);

    sort(str,strSize);

    for(size_t i=0;i<strSize;i++)
        cout << str[i] << endl;

    return 0;
}


hope that helps
Thank you both for your replies. I should've phrased my question more precisely. I already know the problem is with the for loop and I already know it's an easy fix. I would like to know, however, why the program behaves the way it does, i.e. why the program crashes as soon as c == 0. Shouldn't the for loop simply be skipped as soon as i < -1?

Perhaps the following will lend some insight:

1
2
3
4
5
6
#include <iostream>

int main()
{
    std::cout << std::size_t(-1) << '\n' ;
}


http://ideone.com/F5rADw

Thanks, it sure did. I already suspected integer wrapping to be the problem, yet somehow I was stupid enough to only change the counter to int and not the second parameter. The function now works as expected.
Topic archived. No new replies allowed.