I'm working on my c++ assignment (bubble sort), but i 'm stuck on my code. Is there anybody know how to print out the array contents after each pass of the sort? Should I use a for loop or a function call to print out??
thanks

int first_array[8] = {13, 9, 36, 47, 3, 88, 7, 100};

Here 's my code:

#include "stdafx.h"
#include <iostream>
using namespace std;

// Function prototypes
void sortArray(int[], int);
void showArray(int[], int);

int main()
{
	// Array of unsorted numers.
	int numbers[8] = {13, 9, 36, 47, 3, 88, 7, 100};
		
	// Display the numbers.
	cout << " The unsorted numbers are: " << endl;
	showArray(numbers, 8);

	// Sort the numbers.
	sortArray(numbers, 8);

	// Display them again.
	cout << " \nThe sorted numbers are: " << endl;
	showArray(numbers, 8);
	return 0;
}

//***********************************************************
// Definition of function sortArray							*
// This function performs an ascending order bubble sort on *
// array. size is the number of elements in the array.		*
//***********************************************************

void sortArray(int array[], int size)
{
	bool swap;
	int temp;

	do
	{
		swap = false;
		for(int count = 0;count < (size - 1); count++)
		{
			if (array[count] > array[count + 1])
			{
				temp = array[count];
				array[count] = array[count + 1];
				array[count + 1] = temp;
				swap = true;
			}
		}
	}while(swap);
}

//***********************************************************
// Definition of function showArray.						*						
// This function displays the contents of array. size is	*
// the number of element.									*
//***********************************************************

void showArray(int array[], int size)
{
	for (int count = 0;count < size; count++)
		cout << array[count] << " ";
	
}

Recommended Answers

All 3 Replies

just add showArray() function call on line 51 of the code you posted, just before the end of that do loop.

Your sort array needs another for loop.

Your sort array needs another for loop.

No it doesn't.

The do...while is the outer loop, continues until a pass of the inner for loop goes without any swap occurring.

However, it is less efficient than it could be, as it keeps comparing at the far end of the array, which holds the already sorted elements.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.