0

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 by WaltP: Added CODE tags -- with all the help about them, how could you miss using them????

4
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by vmanes
0

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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.