Home Forums C Programming beginners needs help Re: Re: beginners needs help

#3619
GWILouisaxwzkla
Participant

Don’t know what type of sort you need to use but heres one with bubble sort:



/****************************************************************
* File Name : c:programstempCG.cpp
* Date : December,29,2009
* Comments : new project
* Compiler/Assembler : Visual C++ 6.0
* Modifications :
*
*
*
*
*
* Program Shell Generated At: 11:37:28 a.m.
=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/


#include < iostream >
//#include < string.h >
//#include < conio.h >
//#include < math.h >
//#include < iomanip >
//#include < ctype.h >

using namespace std;


void bubbleSort ( int * array , int numberItems );


//main function ******************************

const int MAX_NUMBERS = 20;

int main ( )
{

int input;
int numberOfInputItems;
int numberCount = 0;
int numbers [ MAX_NUMBERS ];

cout << "Enter number of items to input: ";
cin >> numberOfInputItems;

int i = 0;
while ( i < numberOfInputItems )
{
cout << "enter a number: ";
cin >> numbers [ i ] ;
if ( numbers [ i ] == 1 || numbers [ i ] == 4 || numbers [ i ] == 5 || numbers [ i ] == 12 ||
numbers [ i ] || numbers [ i ] == 3 )
numberCount ++;
i ++;
}

cout << endl;
cout << "The count was " << numberCount << endl << endl;

bubbleSort ( numbers , i );

int j = 0;
while ( j < i )
{
cout << numbers [ j ] << " ";
j ++;
}
}

/******************************* FUNCTION DEFINITION ******************************

Name : bubbleSort
Parameters :

array a(n) int * ,
numberItems a(n) int


Returns: Void type
Comments:



++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
void bubbleSort ( int * array , int numberItems )
{

int endSortedArray = numberItems - 1;
int lastSwapIndex;
int temp;
while ( endSortedArray > 0 ) //while not at the end of the unsorted array
{
lastSwapIndex = 0; //save index of the last item swapped
int i = 0; //start at the beggining of the unsorted array
while ( i < endSortedArray ) //while not in the sorted items
{
if ( array [ i ] > array [ i + 1 ] ) //if current item is smaller than next , bubble up
{
//swap array [ i ] and array [ i + 1 ]
temp = array [ i ];
array [ i ] = array [ i + 1 ];
array [ i + 1 ] = temp;
lastSwapIndex = i;
}
i ++;
}
endSortedArray = lastSwapIndex; //reset swap boundry
}



return;
}