Click here to Skip to main content
15,881,881 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to count positive values WHILE doing HeapSort? Here is my HeapSort and I count them in a loop at the end of the method, but it needs to be done while sorting. How's that?

C++
void Sift(int arr[], int left, int right)
{
	int i, j, x;
    
	i = left;
        j = 2 * i + 1;
	x = arr[i];
            
	while (j <= right)
	{
		if(j < right)
			if(arr[j] < arr[j + 1]) j++;
		
		if (x >= arr[j]) break;

		arr[i] = arr[j];
		i = j;
		j = 2 * i + 1;
	}
	
	arr[i] = x;
}

void HeapSort(int arr[], int n)
{
    int left, right, temp;

    left = n / 2 + 1;
    right = n - 1;

    while (0 < left)
    {
	left--;
                    
	Sift(arr, left, right);
    }

    while (0 < right)
    {
        temp = arr[left];
	arr[left] = arr[right];
	arr[right] = temp;

        right--;

	Sift(arr, left, right);
    }

    for(int i = 0; i < n; i++)
	if(0 < arr[i]) PosCount++;
}
Posted

Why?

It's not going to be faster.

The sort is O(n log n). So the fastest you could hope to be while doing it during the sort is O(n log n) comparsions (and you can't do it in one comparison).

The loop at the end is O(n). And if you want to speed that up, do it as:

C++
int i = 0;
while (0 < arr[i] && i < n)
   i++;

int PosCount = n - i;


Which is O(n).

Or if you expect n to be huge, do a binary search:

C++
left = 0;
right = n - 1;
while (left > right) {
   int i = (left + right)/2;
   if (0 < arr[i]) {
       right = i;
   } else {
       left = i;
   }
}
int PosCount = n - left;


Which is O(log n)

The only reason I could see for wanting to count the positive numbers while sorting is either this is a homework assignement, or the array is much larger than physical memory and you don't want to incurr the cost of paging it all in again. But if that's the case, the heap sort is going to cause all kinds of memory thrashing and that'll be a worse problem then your nice linear or binary search.
 
Share this answer
 
There is no reason to loop over all of the values which requires a O(n) operation for an algorithm that is O(n logn).
Since you will have a sorted array in the end, the "trick" is:

During your heapsort identify the point in the code where the first positive integer resides.
The number of positive integers can then be calculated by:

Size - Index of first positive integer

which will add O(k) complexity to your algorithm, which will be negligible.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900