Heapsort with a selectable amount of children - c++

Im trying to write some code that could sort an array using heapsort. The heap have two children right now but i want the user to be able to choose the amount of children in the heap(d in the function heapsort).
Question: How do i make the function heapsort able to recieve a number (d) from the user and sort the array with heapsort with that amount of children?
template <typename T>
void heapify(T arr[], int n, int i) {
int biggest = i;
int leftChild = 2 * i + 1;
int rightChild = 2 * i + 2;
if (leftChild < n && arr[leftChild] > arr[biggest])
{
biggest = leftChild;
}
if (rightChild < n && arr[rightChild] > arr[biggest]) {
biggest = rightChild;
}
if (biggest != i) {
swap(arr[i], arr[biggest]);
heapify(arr, n, biggest);
}
}
template <typename T>
void heapsort(T arr[], int n, int d)
{
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}
for (int i = n - 1; i > 0; i--) {
swap(arr[0], arr[i]);
heapify(arr, i, 0);
}
}

Just because you made it so easy:
template <typename T>
void heapify(T arr[], int n, int d, int i) {
int biggest = i;
int childrenStart = d * i + 1;
int childrenEnd = childrenStart + d;
if (childrenEnd > n) {
childrenEnd = n;
}
for (int child = childrenStart; child < childrenEnd; ++child) {
if (arr[child] > arr[biggest]) {
biggest = child;
}
}
if (biggest != i) {
swap(arr[i], arr[biggest]);
heapify(arr, n, d, biggest);
}
}
template <typename T>
void heapsort(T arr[], int n, int d)
{
if (n<=0) {
return;
}
for (int i = (n-2) / d; i >= 0; i--) {
heapify(arr, n, d, i);
}
for (int i = n - 1; i > 0; i--) {
swap(arr[0], arr[i]);
heapify(arr, i, d, 0);
}
}

Related

Why the quickest sort algorithm is always merge sort among merge,insertion,quick sort and heap sort when I am writing a c++ function to test?

Book page 1
Book page 2
The 4th question is my homework. I am asked to write 4 sort functions to compare the worst time they use. The length is n.
My code is as follows
#include<vector>
using namespace std;
void Swap(int &a,int &b)
{
int temp=a;
a=b;
b=temp;
}
void partition(int *a, int left, int right){
int mid = (left+right)/2;
int t1 = a[left], t2 = a[mid], t3 = a[right];
if((t1 <= t2 && t2 <= t3) || (t3 <= t2 && t2 <= t1))
{Swap(a[right], a[mid]);}
else if((t2 <= t1 && t1 <= t3) || (t3 <= t1 && t1 <=t2))
{Swap(a[right], a[left]);}
}
void QuickSort(int* a,int left,int right)
{
if(left<right)
{
int i;
i=left;
int j;
j=right+1;
partition(a,left,right);
int mid = (left+right)/2;
int t1 = a[left], t2 = a[mid], t3 = a[right];
if((t1 <= t2 && t2 <= t3) || (t3 <= t2 && t2 <= t1))
{Swap(a[right], a[mid]);}
else if((t2 <= t1 && t1 <= t3) || (t3 <= t1 && t1 <=t2))
{Swap(a[right], a[left]);}
int pivot=a[left];
do{
do i++;while(a[i]<pivot);
do j--;while(a[j]>pivot);
if(i<j) Swap(a[i],a[j]);
}while(i<j);
Swap(a[left],a[j]);
QuickSort(a,left,j-1);
QuickSort(a,j+1,right);
}
}
void InsertSort(int* arr, int n)
{
for (int i = 0; i < n; i++) {
for (int j = i; j > 0; j--) {
if (arr[j] < arr[j-1]) {
Swap(arr[j], arr[j - 1]);
}
}
}
}
void Merge(int *initList,int* mergedList,int l,int m,int n)
{
int i1=l,iResult=l,i2=m+1;
for(;i1<=m&&i2<=n;iResult++)
{
if(initList[i1]<=initList[i2])
{
mergedList[iResult]=initList[i1];
i1++;
}
else
{
mergedList[iResult]=initList[i2];
i2++;
}
}
for(int temp=iResult;i1<m+1;i1++,temp++)
{
mergedList[temp]=initList[i1];
}
for(int temp=iResult;i2<n+1;i2++,temp++)
{
mergedList[temp]=initList[i2];
}
}
void MergePass(int *initList,int *resultList,int n,int s)
{
int i=1;
for(;i<=n-2*s+1;i+=2*s)
{
Merge(initList,resultList,i,i+s-1,i+2*s-1);
}
if((i+s-1)<n)Merge(initList,resultList,i,i+s-1,n);
else
for(int temp=i;temp<n+1;temp++)
{
resultList[temp]=initList[temp];
}
}
void MergeSort(int* a,int n)
{
int *tempList=new int[n+1];
for(int i=1;i<n;i*=2)
{
MergePass(a,tempList,n,i);
i*=2;
MergePass(tempList,a,n,i);
}
for(int i=0;i<n+1;i++)
{
a[i]=tempList[i];
}
delete[]tempList;
}
void adjustHeap(int* arr, int i, int length) {
int temp = arr[i];//先取出当前元素i
for (int k = i * 2 + 1; k <=length; k = k * 2 + 1) {
if (k + 1 <=length && arr[k] < arr[k + 1]) {
k++;
}
if (arr[k] > temp) {
arr[i] = arr[k];
i = k;
} else {
break;
}
}
arr[i] = temp;
}
void adjust_heap(int* a, int father, int len)
{
int left = 2 * father;
int right = 2 * father + 1;
int max = father;
if( left <= len && a[left] > a[max])
max = left;
if( right <= len && a[right] > a[max])
max = right;
if(max != father)
{
Swap( a[max], a[father]);
adjust_heap(a, max, len);
}
}
void HeapSort(int* a, int len)
{
for(int i = len / 2; i >= 1; --i)
adjust_heap(a, i, len);
for(int i = len; i >= 1; --i)
{
Swap(a[1], a[i]);
adjust_heap(a, 1, i - 1);
}
for(int i=0;i<len;i++)
a[i]=a[i+1];
}
void heapAdjust(int*nums, int idx,int len){
int temp=nums[idx];
for(int j=idx*2+1;j<len;j=j*2+1){
if(j+1<len&&nums[j]<nums[j+1]) {j++;}
if(temp>nums[j]) {break;}
nums[idx]=nums[j];
idx =j;
}
nums[idx]=temp;
}
void heapSort(int* nums, int n,int k){
for(int i=n/2-1;i>=0;i--)
{
heapAdjust(nums, i,n);
}
for(int i=n-1;i>0;i--)
{
if(k) {k--;}
else {break;}
swap(nums[0],nums[i]);
heapAdjust(nums,0,i);
}
}
void MaxMerge(int arr[],int l,int r)//transform the array so it is the most complex for merge sorting
{
if(r-l>1)
{
int *temp=new int[r-l+3];
temp[0]=0;
for(int i=0,j=1;i<=r-l;i++)
{
if(i%2==0){
temp[j+(r-l+1)/2]=arr[i+l];
}
else{
temp[j]=arr[i+l];
j++;
}
}
for(int i=l,j=1;i<=r;)
{
arr[i]=temp[j];
i++;
j++;
}
delete[]temp;
MaxMerge(arr,l+(r-l)/2,r);
MaxMerge(arr,l,l+(r-l)/2-1);
}
else
{
int t=arr[l];
arr[l]=arr[r];
arr[r]=t;
}
}
void Permute(int *a,int n)
{
srand(time(0));
for(int i=n;i>=2;i--)
{
int j=rand()%i+1;
swap(a[j],a[i]);
}
}
void TimeTest(int n)
{
if(n!=0){
int *QuickSortTest=new int[n+1];
int *InsertSortTest=new int[n+1];
int *HeapSortTest=new int[n+1];
int *MergeSortTest=new int[n+1];
for(int j=0;j<n+1;j++)
{
QuickSortTest[j]=j;
InsertSortTest[j]=n-j;
MergeSortTest[j]=j;
HeapSortTest[j]=j;
}
MaxMerge(MergeSortTest,1,n);
Permute(HeapSortTest,n);
clock_t begin1=clock();
for(int j=0;j<500;j++)
{
QuickSort(QuickSortTest,1,n);
}
clock_t end1=clock();
clock_t begin2=clock();
for(int j=0;j<500;j++)
{
heapSort(HeapSortTest,n,n-1);
}
clock_t end2=clock();
clock_t begin3=clock();
for(int j=0;j<500;j++)
{
InsertSort(QuickSortTest,n);
}
clock_t end3=clock();
clock_t begin4=clock();
for(int j=0;j<500;j++)
{
MergeSort(QuickSortTest,n);
}
clock_t end4=clock();
cout<<"n="<<n<<" QuickSort: "<<end1-begin1<<endl;
cout<<"n="<<n<<" HeapSort: "<<end2-begin2<<endl;
cout<<"n="<<n<<" InsertSort: "<<end3-begin3<<endl;
cout<<"n="<<n<<" MergeSort: "<<end4-begin4<<endl;
delete[]QuickSortTest;
delete[]InsertSortTest;
delete[]HeapSortTest;
delete[]MergeSortTest;
}
}
int main()
{
//int num1[]={500,1000,2000,4000,3000};
for(int i=0;i<=4000;i+=100)
{TimeTest(i);cout<<endl;}
}
I have already test for every function, and they are all right.
However,the result is that
I am confused that why merge sorting is always the quickest?
Both your algorithms and tests need some tender loving care.
For example I replace your InsertSort with less naive version of it
void InsertSort(int* arr, int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
After that InsertSort suddenly starts to wash floors with others in your tests. That is so because the test arrays are already sorted in most of the runs and it is rather good with such.
Among your original algorithms MergeSort was best with sorted input and so it won.

C++ Quicksort with vectors

The quicksort function works perfectly fine as ive tried it with the standard array. When using vectors however, I get an error message saying swap function doesnt take 3 arguments. Any help would be appreciated.
void quicksort(vector<int> &vec, int L, int R) {
int i, j, mid, piv;
i = L;
j = R;
mid = L + (R - L) / 2;
piv = vec[mid];
while (i<R || j>L) {
while (vec[i] < piv)
i++;
while (vec[j] > piv)
j--;
if (i <= j) {
swap(vec, i, j); //error=swap function doesnt take 3 arguments
i++;
j--;
}
else {
if (i < R)
quicksort(vec, i, R);
if (j > L)
quicksort(vec, L, j);
return;
}
}
}
void swap(vector<int> v, int x, int y) {
int temp = v[x];
v[x] = v[y];
v[y] = temp;
}
int main() {
vector<int> vec1;
const int count = 10;
for (int i = 0; i < count; i++) {
vec1.push_back(1 + rand() % 100);
}
quicksort(vec1, 0, count - 1);
}
See
void quicksort(vector<int> &vec, int L, int R)
and
void swap(vector<int> v, int x, int y)
The first parameter does not use reference.
Like various comment say, problem is that your version of swap is being confused with std::swap. You can fix it by either moving the implementation of swap before you use it or add a declaration before you use it.
Also per Devin's answer, pass by reference so you get the swapped values back.
Here is the fixed code:
#include <vector>
using namespace std;
void swap(vector<int>& v, int x, int y);
void quicksort(vector<int> &vec, int L, int R) {
int i, j, mid, piv;
i = L;
j = R;
mid = L + (R - L) / 2;
piv = vec[mid];
while (i<R || j>L) {
while (vec[i] < piv)
i++;
while (vec[j] > piv)
j--;
if (i <= j) {
swap(vec, i, j); //error=swap function doesnt take 3 arguments
i++;
j--;
}
else {
if (i < R)
quicksort(vec, i, R);
if (j > L)
quicksort(vec, L, j);
return;
}
}
}
void swap(vector<int>& v, int x, int y) {
int temp = v[x];
v[x] = v[y];
v[y] = temp;
}
int main() {
vector<int> vec1;
const int count = 10;
for (int i = 0; i < count; i++) {
vec1.push_back(1 + rand() % 100);
}
quicksort(vec1, 0, count - 1);
}

How to implement a max heap

I have the code to build a max heap, but it keeps on returning the same array I give it. I'm sure its a minor error, but I cant seem to figure it out. Any help is appreciated.
Compilable sample code:
#include <iostream>
#include <cmath>
class Heaparr {
public:
Heaparr();
void insert(int da);
int getLeft(int i) { return 2 * i; }
int getRight(int i) { return (2 * i) + 1; }
int getParent(int i) { return i / 2; }
int getMax() { return maxHeap[0]; }
void print();
void reheap(int num);
void makeArray();
void Build_Max_Heap(int maxHeap[], int heap_size);
void Max_Heapify(int heapArray[], int i, int heap_size);
void heapSort(int heapArray[]);
private:
int size;
int* maxHeap;
int index;
int i;
};
Heaparr::Heaparr() {
maxHeap = nullptr;
size = 0;
}
void Heaparr::insert(int da) {
size++;
int* tmp = new int[size];
for (int i = 0; i < size - 1; i++) {
tmp[i] = maxHeap[i];
}
tmp[size - 1] = da;
delete[] maxHeap;
maxHeap = tmp;
}
void Heaparr::heapSort(int maxHeap[]) {
int heap_size = size;
int n = size;
int temp;
Build_Max_Heap(maxHeap, heap_size);
for (int i = n - 1; i >= 1; i--) {
temp = maxHeap[0];
maxHeap[0] = maxHeap[i];
maxHeap[i] = temp;
heap_size = heap_size - 1;
Max_Heapify(maxHeap, 0, heap_size);
}
for (int i = 0; i < 8; i++) {
std::cout << maxHeap[i] << std::endl;
}
}
void Heaparr::Build_Max_Heap(int maxHeap[], int heap_size) {
int n = size;
for (int i = floor((n - 1) / 2); i >= 0; i--) {
Max_Heapify(maxHeap, i, heap_size);
}
return;
}
void Heaparr::Max_Heapify(int heapArray[], int i, int heap_size) {
// int n = size;
int largest = 0;
int l = getLeft(i);
int r = getRight(i);
if ((l <= heap_size) && (heapArray[l] > heapArray[i])) {
largest = l;
} else {
largest = i;
}
if ((r <= heap_size) && (heapArray[r] > heapArray[largest])) {
largest = r;
}
int temp;
if (largest != i) {
temp = heapArray[i];
heapArray[i] = heapArray[largest];
heapArray[largest] = temp;
Max_Heapify(heapArray, largest, heap_size);
}
return;
}
int main(int argc, char* argv[]) {
int hArray[8] = {5, 99, 32, 4, 1, 12, 15, 8};
Heaparr t;
t.heapSort(hArray);
for (auto v : hArray) {
std::cout << v << ", ";
}
std::cout << std::endl;
}
I made some fixed to the code (i try not to changed much the original code):
The getLeft, getRight and getParent formulas were wrong (ex: when i == 0 children must be 1 and 2 and with your code are 0 and 1. The return type was also wrong, should be int (array index).
Do you receive in all methods a int[] except in insert and the member variable that are double[], changed all to int[], if you need changed back all to double
Using std::swap for swap values in the array.
Adding the length of the array to heapSort (inside the method this info is lost, need to be passed by parameter).
Notes:
I dont see where you use the member variable maxHeap, because all methods except getMax and insert use the array passed by parameter and not the member variable (perhaps you should initialized in the constructor or in heapSort method.
Try to use std::vector instead of C Array
Code:
#include <iostream>
#include <cmath>
class Heaparr {
public:
Heaparr();
void insert(int da);
int getLeft(int i) { return 2 * i + 1; }
int getRight(int i) { return 2 * i + 2; }
int getParent(int i) { return (i - 1) / 2; }
int getMax() { return maxHeap[0]; }
void print();
void reheap(int num);
void makeArray();
void Build_Max_Heap(int heapArray[], int heap_size);
void Max_Heapify(int heapArray[], int i, int heap_size);
void heapSort(int heapArray[], int heap_size);
private:
int size;
int* maxHeap;
int index;
int i;
};
Heaparr::Heaparr() {
maxHeap = nullptr;
size = 0;
}
void Heaparr::insert(int da) {
size++;
int* tmp = new int[size];
for (int i = 0; i < size - 1; i++) {
tmp[i] = maxHeap[i];
}
tmp[size - 1] = da;
delete[] maxHeap;
maxHeap = tmp;
}
void Heaparr::heapSort(int heapArray[], int heap_size) {
size = heap_size;
int n = size;
Build_Max_Heap(heapArray, heap_size);
for (int i = n - 1; i >= 1; i--) {
std::swap(heapArray[0], heapArray[i]);
heap_size = heap_size - 1;
Max_Heapify(heapArray, 0, heap_size);
}
}
void Heaparr::Build_Max_Heap(int heapArray[], int heap_size) {
int n = size;
for (int i = floor((n - 1) / 2); i >= 0; i--) {
Max_Heapify(heapArray, i, heap_size);
}
return;
}
void Heaparr::Max_Heapify(int heapArray[], int i, int heap_size) {
// int n = size;
int largest = 0;
int l = getLeft(i);
int r = getRight(i);
if ((l < heap_size) && (heapArray[l] < heapArray[i])) {
largest = l;
} else {
largest = i;
}
if ((r < heap_size) && (heapArray[r] < heapArray[largest])) {
largest = r;
}
if (largest != i) {
std::swap(heapArray[i], heapArray[largest]);
Max_Heapify(heapArray, largest, heap_size);
}
return;
}
int main(int argc, char* argv[]) {
int hArray[8] = {5, 99, 32, 4, 1, 12, 15, 8};
Heaparr t;
t.heapSort(hArray, sizeof(hArray)/sizeof(hArray[0]));
for (auto v : hArray) {
std::cout << v << ", ";
}
std::cout << std::endl;
return 0;
}
Output:
99, 32, 15, 12, 8, 5, 4, 1,
Tested in GCC 4.9.0 with C++11
If you're willing to consider alternative implementations, then here is one:
#define MIN_TYPE 0
#define MAX_TYPE ~0
template<int TYPE,typename ITEM>
class Heap
{
public:
Heap(int iMaxNumOfItems);
virtual ~Heap();
public:
bool AddItem(ITEM* pItem);
bool GetBest(ITEM** pItem);
protected:
int BestOfTwo(int i,int j);
void SwapItems(int i,int j);
protected:
ITEM** m_aItems;
int m_iMaxNumOfItems;
int m_iCurrNumOfItems;
};
template<int TYPE,typename ITEM>
Heap<TYPE,ITEM>::Heap(int iMaxNumOfItems)
{
m_iCurrNumOfItems = 0;
m_iMaxNumOfItems = iMaxNumOfItems;
m_aItems = new ITEM*[m_iMaxNumOfItems];
if (!m_aItems)
throw "Insufficient Memory";
}
template<int TYPE,typename ITEM>
Heap<TYPE,ITEM>::~Heap()
{
delete[] m_aItems;
}
template<int TYPE,typename ITEM>
bool Heap<TYPE,ITEM>::AddItem(ITEM* pItem)
{
if (m_iCurrNumOfItems == m_iMaxNumOfItems)
return false;
m_aItems[m_iCurrNumOfItems] = pItem;
for (int i=m_iCurrNumOfItems,j=(i+1)/2-1; j>=0; i=j,j=(i+1)/2-1)
{
if (BestOfTwo(i,j) == i)
SwapItems(i,j);
else
break;
}
m_iCurrNumOfItems++;
return true;
}
template<int TYPE,typename ITEM>
bool Heap<TYPE,ITEM>::GetBest(ITEM** pItem)
{
if (m_iCurrNumOfItems == 0)
return false;
m_iCurrNumOfItems--;
*pItem = m_aItems[0];
m_aItems[0] = m_aItems[m_iCurrNumOfItems];
for (int i=0,j=(i+1)*2-1; j<m_iCurrNumOfItems; i=j,j=(i+1)*2-1)
{
if (j+1 < m_iCurrNumOfItems)
j = BestOfTwo(j,j+1);
if (BestOfTwo(i,j) == j)
SwapItems(i,j);
else
break;
}
return true;
}
template<int TYPE,typename ITEM>
int Heap<TYPE,ITEM>::BestOfTwo(int i,int j)
{
switch (TYPE)
{
case MIN_TYPE: return *m_aItems[i]<*m_aItems[j]? i:j;
case MAX_TYPE: return *m_aItems[i]>*m_aItems[j]? i:j;
}
throw "Illegal Type";
}
template<int TYPE,typename ITEM>
void Heap<TYPE,ITEM>::SwapItems(int i,int j)
{
ITEM* pItem = m_aItems[i];
m_aItems[i] = m_aItems[j];
m_aItems[j] = pItem;
}
And here is a usage example:
typedef int ITEM;
#define SIZE 1000
#define RANGE 100
void test()
{
ITEM* pItem;
ITEM aArray[SIZE];
Heap<MIN_TYPE,ITEM> cHeap(SIZE);
srand((unsigned int)time(NULL));
for (int i=0; i<SIZE; i++)
{
aArray[i] = rand()%RANGE;
cHeap.AddItem(aArray+i);
}
for (int i=0; i<SIZE; i++)
{
cHeap.GetBest(&pItem);
printf("%d\n",*pItem);
}
}
Description:
This class stores up to N items of type T
It allows adding an item or extracting the best item
Supported operations are accomplished at O(log(n)), where n is the current number of items
Remarks:
T is determined at declaration and N is determined at initialization
The meaning of "best", either minimal or maximal, is determined at declaration
In order to support Heap<MIN,T> and Heap<MAX,T>, one of the following options must be viable:
bool operator<(T,T) and bool operator>(T,T)
bool T::operator<(T) and bool T::operator>(T)
T::operator P(), where P is a type, for which, one of the above options is viable

Algorithm that builds heap

I am trying to implement build_max_heap function that creates the heap( as it is written in Cormen's "introduction do algorithms" ). But I am getting strange error and i could not localize it. My program successfully give random numbers to table, show them but after build_max_heap() I am getting strange numbers, that are probably because somewhere my program reached something out of the table, but I can not find this error. I will be glad for any help.
For example I get the table:
0 13 18 0 22 15 24 19 5 23
And my output is:
24 7 5844920 5 22 15 18 19 0 23
My code:
#include <iostream>
#include <ctime>
#include <stdlib.h>
const int n = 12; // the length of my table, i will onyl use indexes 1...n-1
struct heap
{
int *tab;
int heap_size;
};
void complete_with_random(heap &heap2)
{
srand(time(NULL));
for (int i = 1; i <= heap2.heap_size; i++)
{
heap2.tab[i] = rand() % 25;
}
heap2.tab[0] = 0;
}
void show(heap &heap2)
{
for (int i = 1; i < heap2.heap_size; i++)
{
std::cout << heap2.tab[i] << " ";
}
}
int parent(int i)
{
return i / 2;
}
int left(int i)
{
return 2 * i;
}
int right(int i)
{
return 2 * i + 1;
}
void max_heapify(heap &heap2, int i)
{
if (i >= heap2.heap_size || i == 0)
{
return;
}
int l = left(i);
int r = right(i);
int largest;
if (l <= heap2.heap_size || heap2.tab[l] > heap2.tab[i])
{
largest = l;
}
else
{
largest = i;
}
if (r <= heap2.heap_size || heap2.tab[r] > heap2.tab[i])
{
largest = r;
}
if (largest != i)
{
std::swap(heap2.tab[i], heap2.tab[largest]);
max_heapify(heap2, largest);
}
}
void build_max_heap(heap &heap2)
{
for (int i = heap2.heap_size / 2; i >= 1; i--)
{
max_heapify(heap2, i);
}
}
int main()
{
heap heap1;
heap1.tab = new int[n];
heap1.heap_size = n - 1;
complete_with_random(heap1);
show(heap1);
std::cout << std::endl;
build_max_heap(heap1);
show(heap1);
}
Indeed, the table is accessed with out-of-bounds indexes.
if (l <= heap2.heap_size || heap2.tab[l] > heap2.tab[i])
^^
I think you meant && in this condition.
The same for the next branch with r.
In case you're still having problems, below is my own implementation that you might use for reference. It was also based on Cormen et al. book, so it's using more or less the same terminology. It may have arbitrary types for the actual container, the comparison and the swap functions. It provides a public queue-like interface, including key incrementing.
Because it's part of a larger software collection, it's using a few entities that are not defined here, but I hope the algorithms are still clear. CHECK is only an assertion mechanism, you can ignore it. You may also ignore the swap member and just use std::swap.
Some parts of the code are using 1-based offsets, others 0-based, and conversion is necessary. The comments above each method indicate this.
template <
typename T,
typename ARRAY = array <T>,
typename COMP = fun::lt,
typename SWAP = fun::swap
>
class binary_heap_base
{
protected:
ARRAY a;
size_t heap_size;
SWAP swap_def;
SWAP* swap;
// 1-based
size_t parent(const size_t n) { return n / 2; }
size_t left (const size_t n) { return n * 2; }
size_t right (const size_t n) { return n * 2 + 1; }
// 1-based
void heapify(const size_t n = 1)
{
T& x = a[n - 1];
size_t l = left(n);
size_t r = right(n);
size_t select =
(l <= heap_size && COMP()(x, a[l - 1])) ?
l : n;
if (r <= heap_size && COMP()(a[select - 1], a[r - 1]))
select = r;
if (select != n)
{
(*swap)(x, a[select - 1]);
heapify(select);
}
}
// 1-based
void build()
{
heap_size = a.length();
for (size_t n = heap_size / 2; n > 0; n--)
heapify(n);
}
// 1-based
size_t advance(const size_t k)
{
size_t n = k;
while (n > 1)
{
size_t pn = parent(n);
T& p = a[pn - 1];
T& x = a[n - 1];
if (!COMP()(p, x)) break;
(*swap)(p, x);
n = pn;
}
return n;
}
public:
binary_heap_base() { init(); set_swap(); }
binary_heap_base(SWAP& s) { init(); set_swap(s); }
binary_heap_base(const ARRAY& a) { init(a); set_swap(); }
binary_heap_base(const ARRAY& a, SWAP& s) { init(a); set_swap(s); }
void init() { a.init(); build(); }
void init(const ARRAY& a) { this->a = a; build(); }
void set_swap() { swap = &swap_def; }
void set_swap(SWAP& s) { swap = &s; }
bool empty() { return heap_size == 0; }
size_t size() { return heap_size; }
size_t length() { return heap_size; }
void reserve(const size_t len) { a.reserve(len); }
const T& top()
{
CHECK (heap_size != 0, eshape());
return a[0];
}
T pop()
{
CHECK (heap_size != 0, eshape());
T x = a[0];
(*swap)(a[0], a[heap_size - 1]);
heap_size--;
heapify();
return x;
}
// 0-based
size_t up(size_t n, const T& x)
{
CHECK (n < heap_size, erange());
CHECK (!COMP()(x, a[n]), ecomp());
a[n] = x;
return advance(n + 1) - 1;
}
// 0-based
size_t push(const T& x)
{
if (heap_size == a.length())
a.push_back(x);
else
a[heap_size] = x;
return advance(++heap_size) - 1;
}
};

Error using Insertion Sort algorithm - array is not sorted exactly.

Here is some working code that implements a modified version of the Quicksort algorithm that uses Insertion Sort for array size n > 8. My test array isn't sorting exactly right, and I think it must be with my implementation of Insertionsort and Insert.
The general form of the recursive Insertionsort algorithm is:
void Insertionsort(int S[], int n)
{
if(n>1)
Insertionsort(S,n-1);
Insert(S,n-1);
}
void Insert(int *S, int k)
{
int key = S[k];
int j = k-1;
while(j>=0 && S[j] > key)
{
S[j+1] = S[j];
j--;
}
S[j+1] = key;
}
Here is my complete working code that does not sort quite exactly right:
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int comparisons = 0;
int compare_qs_m3_ins[12];
// Function prototypes
int partition(int *S,int l, int u);
void exchange(int list[], int p, int q);
void Insert(int S[], int k);
void Insertionsort(int S[], int low, int hi);
void Quicksort_Insert_M3(int S[], int n, int p, int r);
int main()
{
srand (time(NULL));
// Declare all arrays used for testing
int S1_500[500];
int S2_500[500];
int S3_500[500];
int S1_300[300];
int S2_300[300];
int S3_300[300];
int S1_100[100];
int S2_100[100];
int S3_100[100];
int S1_8[8];
int S2_8[8];
int S3_8[8];
// Fill arrays with random integers
for(int i=0; i<500; i++)
{
S1_500[i] = rand()%1000;
S2_500[i] = rand()%1000;
S3_500[i] = rand()%1000;
}
for(int i=0; i<300; i++)
{
S1_300[i] = rand()%1000;
S2_300[i] = rand()%1000;
S3_300[i] = rand()%1000;
}
for(int i=0; i<100; i++)
{
S1_100[i] = rand()%500;
S2_100[i] = rand()%500;
S3_100[i] = rand()%500;
}
for(int i=0; i<8; i++)
{
S1_8[i] = rand()%100;
S2_8[i] = rand()%100;
S3_8[i] = rand()%100;
}
Quicksort_Insert_M3(S1_500,500,0,499);
compare_qs_m3_ins[0] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S2_500,500,0,499);
compare_qs_m3_ins[1] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S3_500,500,0,499);
compare_qs_m3_ins[2] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S1_300,300,0,299);
compare_qs_m3_ins[3] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S2_300,300,0,299);
compare_qs_m3_ins[4] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S3_300,300,0,299);
compare_qs_m3_ins[5] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S1_100,100,0,99);
compare_qs_m3_ins[6] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S2_100,100,0,99);
compare_qs_m3_ins[7] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S3_100,100,0,99);
compare_qs_m3_ins[8] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S1_8,8,0,7);
compare_qs_m3_ins[9] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S2_8,8,0,7);
compare_qs_m3_ins[10] = comparisons;
comparisons = 0;
Quicksort_Insert_M3(S3_8,8,0,7);
compare_qs_m3_ins[11] = comparisons;
comparisons = 0;
//for(int i=0; i<12; i++)
//cout << compare_qs_m3_ins[i] << endl;
for(int i=0;i<499;i++)
cout << S1_500[i] << endl;
}
int partition(int *S,int l, int u)
{
int x = S[l];
int j = l;
for(int i=l+1; i<=u; i++)
{
comparisons++;
if(S[i] < x)
{
j++;
swap(S[i],S[j]);
}
}
int p = j;
swap(S[l],S[p]);
return p;
}
void swap(int &val1, int &val2)
{
int temp = val1;
val1 = val2;
val2 = temp;
}
void exchange(int list[], int p, int q)
{
int temp = list[p];
list[p] = list[q];
list[q] = temp;
}
int Sort3(int list[], int p, int r)
{
int median = (p + r) / 2;
comparisons++;
if(list[p] <= list[median])
{
comparisons++;
if(list[median]>list[r])
{
comparisons++;
if(list[p]<list[r])
{
int temp = list[p];
list[p] = list[r];
list[r] = list[median];
list[median] = temp;
}
else
{
exchange(list,median,r);
}
}
else
;
}
else
{
comparisons++;
if(list[p] > list[r])
{
comparisons++;
if(list[median] < list[r])
{
int temp = list[p];
list[p] = list[median];
list[median] = list[r];
list[r] = temp;
}
else
{
exchange(list,p,r);
}
}
else
{
exchange(list,p,median);
}
}
return list[r];
}
void Insert(int *S, int k)
{
int key = S[k];
int j = k-1;
while(j>=0 && S[j] > key)
{
S[j+1] = S[j];
j--;
comparisons++;
}
comparisons++;
S[j+1] = key;
}
void Insertionsort(int S[], int low, int hi)
{
if((hi-low)+1>1)
Insertionsort(S,low+1,hi);
Insert(S,hi-low);
}
void Quicksort_Insert_M3(int S[], int n, int low, int hi)
{
if((hi-low)<=8)
Insertionsort(S,low,hi);
else
{
if(low < hi)
{
if((low+1) == hi)
{
comparisons++;
if(S[low] > S[hi])
swap(S[low],S[hi]);
}
else
{
Sort3(S,low,hi);
if((low+2)<hi)
{
swap(S[low+1],S[(low+hi)/2]);
int q = partition(S, low+1, hi-1);
Quicksort_Insert_M3(S, n, low, q-1);
Quicksort_Insert_M3(S, n, q+1, hi);
}
}
}
}
}
The function supposed to sort three array elements in ascending order doesn't:
int Sort3(int list[], int p, int r)
{
called only for p + 2 <= r, so
int median = (p + r) / 2;
p < median < r here. Let a = list[p], b = list[median] and c = list[r].
comparisons++;
if(list[p] <= list[median])
{
comparisons++;
if(list[median]>list[r])
{
comparisons++;
if(list[p]<list[r])
{
So here we have a <= b, c < b and a < c, together a < c < b
int temp = list[p];
list[p] = list[r];
list[r] = list[median];
list[median] = temp;
but you place them in order c, a, b. Probably you intended to use if (list[r] < list[p]) there.
}
else
c <= a <= b
{
exchange(list,median,r);
so that arranges them in order a, c, b.
}
}
else
;
}
else
Here, b < a.
{
comparisons++;
if(list[p] > list[r])
{
c < a
comparisons++;
if(list[median] < list[r])
{
Then b < c < a
int temp = list[p];
list[p] = list[median];
list[median] = list[r];
list[r] = temp;
Yup, that's correct.
}
else
c <= b < a
{
exchange(list,p,r);
}
Okedoke.
}
else
{
b < a <= c
exchange(list,p,median);
Okay.
}
}
return list[r];
}
Why does this function return anything? You don't use the return value anyway.
"The general form of the recursive Insertionsort algorithm is" - if you need to have a head-recursive algorithm, yes, otherwise a better version is:
void Insertionsort(int S[], int i, int n)
{
Insert(S, i, n);
if(i < n)
Insertionsort(S, i+1, n);
}
which is much more understandable. Also, you might as well have put the body of Insert into Insertionsort.
I'm not going to try and figure out your overly complicated version of quicksort. A decent quicksort is around 20 lines or less (like this - www.algolist.net/Algorithms/Sorting/Quicksort) (and add another 10 or less for insertion sort). I suggest getting a better understanding by looking at another implementation and rewriting yours.
I believe this could've been asked as an extension of your previous question.