Problem With Bubble Sort Algorithm

I have to bubble sort program for an exercise on Learnccp.com. I'm doing it on Visual Studio Community 2015. When I tried to run the code, it crashed on with an exception on line 43, where my bubble sort function exits.

Here is the code:
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
// bubble_sort.cpp : Defines the entry point for the console application.
//

#include <iostream>
#include <utility>
#include <limits>
#include "keep_window_open.h"

int bubbleSort(int array[], const int size);
void printSortedArray(const int sortedArray);

int main()
{
	const int size{ 9 };
	int array[size] = { 6, 3, 2, 9, 7, 1, 5, 4, 8 };
	int sortedArray = bubbleSort(array, size);
	printSortedArray(sortedArray);
	keep_window_open();
	return 0;
}

int bubbleSort(int array[], const int size)
{
	int smallestIndex = std::numeric_limits<int>::max();
	int largestIndex = std::numeric_limits<int>::min();
	int sortedArray[5];
	
	for (int startIndex = 0; startIndex < size; ++startIndex)
	{
		
		if (array[startIndex] < array[smallestIndex])
		{
			array[smallestIndex] = array[startIndex];
		}
		if (array[startIndex] > array[largestIndex])
		{
			array[largestIndex] = array[startIndex];
		}
		sortedArray[5] = array[5];
	}
	
	return sortedArray[5];
}

void printSortedArray(const int sortedArray)
{
	using namespace std;
	cout << sortedArray << "\n";
}


I'm also not sure if I actually did the sorting algorithm correctly. That and because I'm not actually at the place in LearnCPP where it talks about std::numeric_limits yet, if someone can tell me a simpler equivalent, it'd be appreciated. Thanks in advance.
Here is a better code

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
#include <iostream>

using namespace std;

void bubbleSortArray(int [], int);
void displayArray(int [], int);

const int SIZE = 5;

int main()
{
    int values[SIZE] = {9, 2, 0, 11, 5};
    cout << "The values before the bubble sort is performed are:" << endl;
    displayArray(values, SIZE);
    bubbleSortArray(values, SIZE);
    cout << "The values after the bubble sort is performed are:" << endl;
    displayArray(values, SIZE);
    return 0;
}

void displayArray(int array[], int elems)
{
    for(int count = 0;count < elems;count++)
        cout << array[count] << "  ";
    cout << endl;
}

void bubbleSortArray(int array[], int elems)
{
    bool swap;
    int temp, bottom = elems - 1;
    do
    {
        swap = false;
        for (int count = 0; count < bottom; count++)
        {
            if (array[count] > array[count+1])
            {
                temp = array[count];
                array[count] = array[count+1];
                array[count+1] = temp;
                swap = true;
            }
        }
        bottom--;
    }
    while(swap != false);
}
I put the size as 5 in the sorting function by mistake; the actual size of the array actually is supposed to be 9. And I only wanted to know how to keep the program from crashing, so you just giving me the answer to entire problem isn't what I wanted (thanks, though).

And I only wanted to know how to keep the program from crashing

There were numerous issues with the original code.

Consider this:
1
2
3
4
   	int smallestIndex = std::numeric_limits<int>::max();
	int largestIndex = std::numeric_limits<int>::min();
	cout << "smallestIndex = " << smallestIndex << '\n';
	cout << "largestIndex =  " << largestIndex  << '\n';

On my system the output is:
smallestIndex = 2147483647
largestIndex =  -2147483648


Now let's say you have an array having 9 elements.
valid subscripts range from 0 to 8
Thus array[0] or array[8] are valid.
What about array[smallestIndex] and array[largestIndex]?
Your code attempts to modify those elements, which are quite definitely not within the bounds of the array.

There are other errors. int sortedArray[5] is not needed, but in any case it is misused, again that could cause a crash, if the program ever got that far.


Okay, so now why is it giving an error about wanting a pointer-to-object type as the array subscript? I can't print the whole array correctly like this.

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
#include <iostream>
#include <utility>
#include "keep_window_open.h"

int bubbleSort(int array[], const int size);

int main()
{
	const int size{ 9 };
	int array[size] = { 6, 3, 2, 9, 7, 1, 5, 4, 8 };
	int sortedArray = bubbleSort(array, size);
	for (int index = 0; index < size; ++index)
	{
		std::cout << sortedArray[size] << "\n";
	}
	keep_window_open();
	return 0;
}

int bubbleSort(int array[], const int size)
{
	int smallestIndex = array[0];
	int largestIndex = array[8];
	int* sortedArray = array;

	for (int startIndex = 0; startIndex < size; ++startIndex)
	{
		int currentIndex = startIndex + 1;
		if (array[currentIndex] < array[smallestIndex])
		{
			std::swap(array[currentIndex], array[smallestIndex]);
		}
		if (array[currentIndex] > array[largestIndex])
		{
			std::swap(array[currentIndex], array[largestIndex]);
		}
		sortedArray = array;
	}
	return sortedArray[9];
}


I don't think you need sortedArray, it's just a distraction here. edit: (and in any case it is misused in several different ways).

At lines 12 - 15, just print the individual elements array[index] of your array. Note - the sort function modifies the original array.
Last edited on
Just tell me how to use that correctly, then, in case I want to return the sorted array back to main().

Since it was getting a bit too hard for me, I ended up looking at the Solution presented on the site itself and am now trying to study it. Anyway, I got this from it, having modified it a bit; let me know if I could've done it better:

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
#include <iostream>
#include <utility>
#include "keep_window_open.h"

void bubbleSort(int array[], const int size);
void displaySortedArray(const int array[], const int size);

int main()
{
	using namespace std;
	
	const int size{ 9 };
	int array[size] = { 6, 3, 2, 9, 7, 1, 5, 4, 8 };
	
	bubbleSort(array, size);
	displaySortedArray(array, size);

	keep_window_open();
	return 0;
}

void bubbleSort(int array[], const int size)
{
	using namespace std;
	
	for (int iteration = 0; iteration < size; ++iteration)
	{
		bool swapped{ false };

		for (int currentIndex = 0; currentIndex < size - 1; ++currentIndex)
		{
			if (array[currentIndex] > array[currentIndex + 1])
			{
				swap(array[currentIndex], array[currentIndex + 1]);
				swapped = true;
			}
			if (array[currentIndex] < array[currentIndex + 1])
			{
				continue;
			}
		}

		if (!swapped)
		{
			cout << "Early termination on iteration: " << iteration + 1 << "\n";
		}
	}
}

void displaySortedArray(const int array[], const int size)
{
	using namespace std;
	for (int index = 0; index < size; ++index)
	{
		cout << array[index] << " ";
	}
	cout << "\n";
}
Last edited on
Just tell me how to use that correctly, then, in case I want to return the sorted array back to main().

Well, it's a kind of strange question to answer, since the original array is sorted, so you could just return a pointer to the original array. But that wouldn't particularly be useful.

One way you could do it is to first allocate an array the same size as the original. Copy all the elements from the original to your new array. Then call the function bubbleSort() and pass it your copied array instead of the original.

There are ways to do it using dynamic arrays (new [] and delete []) but I don't recommend that here, it just adds complexity for no real benefit.

The simplest way would be to use a std::vector instead of a plain array, that gives you all sorts of versatility in a safe and controlled manner.
Topic archived. No new replies allowed.