Perform the heapsort with push_heap and pop_heap : vector push pop heap « Vector « C++






Perform the heapsort with push_heap and pop_heap

   
 

#include <iostream>
using std::cout;
using std::endl;

#include <algorithm>
#include <vector>
#include <iterator>

int main()
{
   int a[ 10 ] = { 3, 10, 2, 7, 4, 8, 1, 9, 5, 6 };

   std::vector< int > v( a, a + 10 ); // copy of a
   std::vector< int > v2;
   std::ostream_iterator< int > output( cout, " " );

   for ( int i = 0; i < 10; i++ )
   {
      v2.push_back( a[ i ] );
      std::push_heap( v2.begin(), v2.end() );
      cout << "\nv2 after push_heap(a[" << i << "]): ";
      std::copy( v2.begin(), v2.end(), output );
   }

   for ( int j = 0; j < v2.size(); j++ )
   {
      cout << "\nv2 after " << v2[ 0 ] << " popped from heap\n";
      std::pop_heap( v2.begin(), v2.end() - j );
      std::copy( v2.begin(), v2.end(), output );
   }
   cout << endl;
   return 0;
}

/* 

v2 after push_heap(a[0]): 3
v2 after push_heap(a[1]): 10 3
v2 after push_heap(a[2]): 10 3 2
v2 after push_heap(a[3]): 10 7 2 3
v2 after push_heap(a[4]): 10 7 2 3 4
v2 after push_heap(a[5]): 10 7 8 3 4 2
v2 after push_heap(a[6]): 10 7 8 3 4 2 1
v2 after push_heap(a[7]): 10 9 8 7 4 2 1 3
v2 after push_heap(a[8]): 10 9 8 7 4 2 1 3 5
v2 after push_heap(a[9]): 10 9 8 7 6 2 1 3 5 4
v2 after 10 popped from heap
9 7 8 5 6 2 1 3 4 10
v2 after 9 popped from heap
8 7 4 5 6 2 1 3 9 10
v2 after 8 popped from heap
7 6 4 5 3 2 1 8 9 10
v2 after 7 popped from heap
6 5 4 1 3 2 7 8 9 10
v2 after 6 popped from heap
5 3 4 1 2 6 7 8 9 10
v2 after 5 popped from heap
4 3 2 1 5 6 7 8 9 10
v2 after 4 popped from heap
3 1 2 4 5 6 7 8 9 10
v2 after 3 popped from heap
2 1 3 4 5 6 7 8 9 10
v2 after 2 popped from heap
1 2 3 4 5 6 7 8 9 10
v2 after 1 popped from heap
1 2 3 4 5 6 7 8 9 10

 */        
    
    
  








Related examples in the same category

1.Inserting Elements in a vector Using the push_back Method
2.Demonstrating the STL vector push_back functions
3.Read data from a file and save that to vector