@@ -17,32 +17,88 @@ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON A
1717
1818#include " game.h"
1919
20+ #include < algorithm>
21+
2022#ifdef _WIN32
2123#include " sys/timeb.h"
2224#endif
2325
26+ #include " mtrand.h"
2427int main (int argc, char * argv[])
2528{
29+ mtsrand (0 );
30+
31+ int players = 100000 ;
32+ vector<int > scores1;
33+ scores1.reserve (players);
34+
35+ for (int n = 0 ; n < players; n++)
36+ scores1.push_back ((int )abs ((int )mtrand ()));
37+
38+ vector<int > scores2 = scores1;
39+
40+ vector<int > scores_sorted;
41+ scores_sorted.reserve (players);
42+
43+
44+
45+
2646 struct timeb t1, t2;
2747
2848 ftime (&t1);
2949
30- long sum;
31- for (int n = 0 ; n < 1000000000 ; n++)
50+ // Insertion sort
3251 {
33- sum = 0 ;
34- for (int i = 0 ; i < 1000 ; i++)
35- sum += i;
52+ while (scores1.size ()) // While the list of scores is not empty
53+ {
54+ // Find the highest score (look at every bit of data in the scores list)
55+ int highest = -1 ;
56+ for (size_t i = 0 ; i < scores1.size (); i++)
57+ {
58+ if (highest < 0 || scores1[i] > scores1[highest])
59+ highest = i;
60+ }
61+
62+ // Add it to the end of the sorted array
63+ scores_sorted.push_back (scores1[highest]);
64+
65+ // Remove it from the input array
66+ scores1.erase (scores1.begin ()+highest, scores1.begin ()+highest+1 );
67+ }
3668 }
3769
3870 ftime (&t2);
3971
4072 long elapsed_ms = (long )(t2.time - t1.time ) * 1000 + (t2.millitm - t1.millitm );
4173
42- printf (" Result: %d\n " , sum);
43- printf (" Elapsed: %dms\n " , elapsed_ms);
74+ printf (" Highest score: %d\n " , scores_sorted[0 ]);
75+ printf (" Insertion sort time: %dms\n " , elapsed_ms);
76+
77+
78+ scores_sorted.clear ();
79+
80+ ftime (&t1);
81+
82+ // Heap sort
83+ {
84+ // Build a heap from the scores (every item is bigger than the items below it
85+ std::make_heap (scores2.begin (), scores2.end ());
86+
87+ // While the input list still has items
88+ while (scores2.size ())
89+ {
90+ std::pop_heap (scores2.begin (), scores2.end ());
91+ scores_sorted.push_back (scores2.back ());
92+ scores2.pop_back ();
93+ }
94+ }
95+
96+ ftime (&t2);
4497
98+ elapsed_ms = (long )(t2.time - t1.time ) * 1000 + (t2.millitm - t1.millitm );
4599
100+ printf (" Highest score: %d\n " , scores_sorted[0 ]);
101+ printf (" Heap sort time: %dms\n " , elapsed_ms);
46102
47103
48104
0 commit comments