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] << " ";
	
}

Edited 6 Years Ago by WaltP: Added CODE tags -- with all the help about them, how could you miss using them????

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.

This article has been dead for over six months. Start a new discussion instead.