Sunday, July 26, 2009

C++ one dimensional array question?

I need a program that would read in array integer values (lets say 10 values) and the output would arrange them from highest to lowest value with the count of the number of occurences for each value. (Again only one dimensional array)

C++ one dimensional array question?
Ah yes, sorry. For some reason I believed the program needed to produce unique numbers. Well, this si what happens if you just glance over the specifications.





Now before providing another solution using arrays, I just have one more question. Can you use preimplemented algorithms or do you need to write a sorting function as well? If so, are there any runtime bounds?





--------------------------------------...





Does it need to be an array? If not, here is a very nice and very fast way of doing just what you need.





Insertion O(n lg n); ( for n {= 10} elements )


Occurence checking: O (m) where m = # different items


Output (no repeating elements) O(m);


Output ( with repeating elements) O (n)





So here we go:





#include %26lt;iostream%26gt;


#include %26lt;set%26gt;





#define ITEMS 10





using namespace std;








int


main( int argc, char * args[] )


{


//Storage for numbers


multiset %26lt; int %26gt; values;





//Get input


for ( int i =0; i%26lt; ITEMS; i++ )


{


int number;


cout %26lt;%26lt; "Well? : "%26lt;%26lt; flush;


cin %26gt;%26gt; number;


values.insert( number );


}





//Generate sorted, ascending, unique output


//For descending you would use rbegin();


multiset%26lt; int %26gt; :: iterator I_value;


I_value = values.begin();





while ( I_value != values.end() )


{


cout %26lt;%26lt;"Unique Sorted: "%26lt;%26lt;(*I_value) %26lt;%26lt; "\n" %26lt;%26lt; flush;


I_value = values.upper_bound( *I_value );


}





//Output all numbers in ascending order


for (I_value = values.begin(); I_value != values.end(); I_value ++)


{


cout %26lt;%26lt;"Just Sorted: "%26lt;%26lt;(*I_value) %26lt;%26lt; "\n" %26lt;%26lt; flush;


}





return 0;


}
Reply:Implement above program in array its, easy.


No comments:

Post a Comment