473,385 Members | 1,707 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Heapsort simply skips over sorting step with large arrays

I'm writing a heapsort program. It asks for a value for "max" and creates an array of "max" # random numbers from 1-100, and then enqueues them all into a Priority Queue. Then it asks if you want to print the resulting list, and if you say yes, it dequeues them each into the cout one by one. (I initially made it so it automatically dequeues into another array, and then if you say yes it prints all elements of that array, but I kept getting seg. faults on that.) The problem is, for some bizarre reason, it literally does not sort the elements if the array is big enough. Here's my code:

Expand|Select|Wrap|Line Numbers
  1. #include<iostream>
  2. #include<string>
  3. #include<cstdlib>
  4. using namespace std;
  5.  
  6. void Swap(short& item1, short& item2);
  7.  
  8. template<class ItemType>
  9. class PQType
  10. {
  11. public:
  12.   PQType(long maxItems);
  13.   ~PQType();
  14.   void MakeEmpty();
  15.   bool IsEmpty() const;
  16.   void Enqueue(ItemType newItem);
  17.   short Dequeue();
  18. private:
  19.   long length;
  20.   short* items;
  21.   void ReheapDown(short root, short bottom);
  22.   void ReheapUp(short root, short bottom);
  23. };
  24.  
  25. template<class ItemType>
  26. PQType<ItemType>::PQType(long maxItems)
  27. {
  28.   items = new short[maxItems];
  29.   length = 0;
  30. }
  31.  
  32. template<class ItemType>
  33. void PQType<ItemType>::MakeEmpty()
  34. {
  35.   length = 0;
  36. }
  37.  
  38. template<class ItemType>
  39. PQType<ItemType>::~PQType()
  40. {
  41.   delete [] items;
  42. }
  43.  
  44. template<class ItemType>
  45. void PQType<ItemType>::ReheapDown(short root, short bottom)
  46. {
  47.   short maxChild;
  48.   short rightChild;
  49.   short leftChild;
  50.  
  51.   leftChild = root*2+1;
  52.   rightChild = root*2+2;
  53.   if (leftChild <= bottom)
  54.   {
  55.     if (leftChild == bottom)
  56.       maxChild = leftChild;
  57.     else
  58.     {
  59.       if (items[leftChild] <= items[rightChild])
  60.         maxChild = rightChild;
  61.       else
  62.         maxChild = leftChild;
  63.     }
  64.     if (items[root] < items[maxChild])
  65.     {
  66.       Swap(items[root], items[maxChild]);
  67.       ReheapDown(maxChild, bottom);
  68.     }
  69.   }
  70. }
  71.  
  72. template<class ItemType>
  73. void PQType<ItemType>::ReheapUp(short root, short bottom)
  74. {
  75.   short parent;
  76.  
  77.   if (bottom > root)
  78.   {
  79.     parent = (bottom-1) / 2;
  80.     if (items[parent] < items[bottom])
  81.     {
  82.       Swap(items[parent], items[bottom]);
  83.       ReheapUp(root, parent);
  84.     }
  85.   }
  86. }
  87.  
  88. template<class ItemType>
  89. void PQType<ItemType>::Enqueue(ItemType newItem)
  90. {
  91.   length++;
  92.   items[length-1] = newItem;
  93.   ReheapUp(0, length-1);
  94. }
  95.  
  96. template<class ItemType>
  97. short PQType<ItemType>::Dequeue()
  98. {
  99.   short item = items[0];
  100.   items[0] = items[length-1];
  101.   length--;
  102.   ReheapDown(0, length-1);
  103.   return item;
  104. }
  105.  
  106. template<class ItemType>
  107. bool PQType<ItemType>::IsEmpty() const
  108. {
  109.   return length == 0;
  110. }
  111.  
  112. void Swap(short& item1,short& item2)
  113. {
  114.   short tempnum = item1;
  115.   item1 = item2;
  116.   item2 = tempnum;
  117. }
  118.  
  119. int main()
  120. {
  121.   long max, bin;
  122.   char cr, listYN;
  123.   string nullstring;
  124.   cout << "\nHeapsort Program\n\n";
  125.   cout << "Enter # of elements to generate: ";
  126.   cin >> max;
  127.   short* unsortedList = new short[max];
  128.   short* sortedList = new short[max];
  129.  
  130.   cout << "Generating list of integers...";
  131.   for (long x=0; x<max; x++)
  132.   {
  133.     unsortedList[x] = (rand()%100)+1;
  134.   }
  135.   cout << " done. Press Enter to continue.\n";
  136.   cin.ignore();
  137.   cin.get(cr);
  138.   cout << "Initializing sort...";
  139.   PQType<short> Heap(max);
  140.   for (long y=0; y<max; y++)
  141.   {
  142.     Heap.Enqueue(unsortedList[y]);
  143.   }
  144.   cout << " done. Display list (y/n)? ";
  145.   cin >> listYN;
  146.   if (listYN == 'y' || listYN == 'Y')
  147.   {
  148.     for (long z=0; z<max; z++)
  149.     {
  150.       cout << Heap.Dequeue() << "  ";
  151.     }
  152.   }
  153. }
  154.  
To give a simple example, it will show them in their proper order when the list is a million elements or less (though it segfaults after the first, like, 200), but it shows them in random order when it's 50 million long (and also segfaults after maybe a couple thousand).

Incidentally it also waits until after it has performed an action (generating original array, sorting into heap) to tell you it's starting it, and I have no idea why.

This is using G++ in Ubuntu, by the way.
Nov 1 '07 #1
2 2254
Banfa
9,065 Expert Mod 8TB
Expand|Select|Wrap|Line Numbers
  1. template<class ItemType>
  2. void PQType<ItemType>::ReheapUp(short root, short bottom)
  3. {
  4.   short parent;
  5.  
  6.   if (bottom > root)
  7.   {
  8.     parent = (bottom-1) / 2;
  9.     if (items[parent] < items[bottom])
  10.     {
  11.       Swap(items[parent], items[bottom]);
  12.       ReheapUp(root, parent);
  13.     }
  14.   }
  15. }
  16.  
You have made you class use recursive function calls. When you are talking about using millions of entries you are very likely to run out of stack space at some point.

Also you logic for this particular (and possibly other) function is wrong. the parameter root is never used, but parent is meant to be a binary chop between root and bottom. The Swap does the wrong thing, when items[parent] < items[bottom] what also holds true is that items[parent] < items[parent+1] and items[parent] < items[bottom-1] (assuming more than 2 entries in the list).

By swapping items[parent] and items[bottom] items[parent] ends up in the wrong place.
Nov 2 '07 #2
Well, it seems both of the above conclusions were wrong. In searching through the code looking for some way to resolve the use of recursion, we discovered a fatal flaw: I was using shorts to hold most of the values that would be equal to or approaching my max length (a side effect from when I converted all my ints to shorts to keep the array small... I was trying to just make the items themselves shorts but inadvertently replaced all my ints). I changed them all back to ints and I seem to be good for it.

Thanks anyway. :)
Nov 6 '07 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: why | last post by:
Hi, just been curious. i have learn that quicksorting algorithm is more widely used then heapsort, despite having the same performance indication of O(n log n) anyone knows why? newbie
22
by: mike | last post by:
If I had a date in the format "01-Jan-05" it does not sort properly with my sort routine: function compareDate(a,b) { var date_a = new Date(a); var date_b = new Date(b); if (date_a < date_b)...
18
by: Scott | last post by:
I have a collection where the items in the collection are dates. I want to iterate over the collection and build a value list string for the rowsource of a listbox. The dates in the collection are...
23
by: yatindran | last post by:
hai this is my 2d array. int a = { {5,2,20,1,30,10}, {23,15,7,9,11,3}, {40,50,34,24,14,4}, {9,10,11,12,13,14}, {31,4,18,8,27,17}, {44,32,13,19,41,19}, {1,2,3,4,5,6},
19
by: Owen T. Soroke | last post by:
Using VB.NET I have a ListView with several columns. Two columns contain integer values, while the remaining contain string values. I am confused as to how I would provide functionality to...
3
by: SneakyElf | last post by:
i am very green with c++ so i get stuck on very simple things anyway, i need to write a program that would read data from file (containing names of tv shows and their networks) one line at a time...
7
by: Steve Bergman | last post by:
I'm involved in a discussion thread in which it has been stated that: """ Anything written in a language that is 20x slower (Perl, Python, PHP) than C/C++ should be instantly rejected by users...
5
by: hirsh.dan | last post by:
Hello to all, i have the following functions: string File::readLine(){ char ch; string str; ch = read(); while(ch != LF && ch != CR && ch != -1){ str.append(1,ch); ch = read(); }
5
by: lemlimlee | last post by:
hello, this is the task i need to do: For this task, you are to develop a Java program that allows a user to search or sort an array of numbers using an algorithm that the user chooses. The...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.