Thursday, July 9, 2009

C++ Programming?

I'm trying to write a program that can tell you the three greatest numbers from a list of several hundred numbers.

C++ Programming?
Sort out the array in descending order using bubble sort or any other algorithm. Then display the first three numbers in the array.


// Bubble Sort Function for Descending Order


void bubble_sort(apvector %26lt;int%26gt; %26amp;array)


{


int i, j, flag = 1; // set flag to 1 to begin initial pass


int temp; // holding variable


int arrayLength = array.length( );


for(i = 1; (i %26lt;= arrayLength) %26amp;%26amp; flag; i++)


{


flag = 0;


for (j=0; j %26lt; (arrayLength -1); j++)


{


if (array[j+1] %26gt; array[j]) // ascending order simply changes to %26lt;


{


temp = array[j]; // swap elements


array[j] = array[j+1];


array[j+1] = temp;


flag = 1; // indicates that a swap occurred.


}


}


}


return; //arrays are passed to functions by address; nothing is returned


}
Reply:If thats all you want to do. I would recommend do a search for the largest number from the list. Remember to store where it was found in the array and ignore that spot on the next search. Repeat and it should get you the three greatest the fastest. Theres no point to sorting cause its just a waste of time and not needed.
Reply:something like this:





void threeGreatest(int *numbers, int count)


{


int greatest[3];


greatest[0]=greatest[1]=greatest[2]=numb...


for (int i=1; i%26lt;count; i++) {


if (numbers[i] %26gt; greatest[0]) {


greatest[2] = greatest[1];


greatest[1] = greatest[0];


greatest[0] = numbers[i];


} else if (numbers[i] %26gt; greatest[1]) {


greatest[2] = greatest[1];


greatest[1] = numbers[i];


} else if (numbers[i] %26gt; greatest[2]) {


greatest[2] = numbers[i];


}


}





printf("biggest=%d\n", greatest[0]);


printf("secound biggest=%d\n", greatest[1]);


printf("third biggest=%d\n", greatest[2]);


}


No comments:

Post a Comment