diff --git a/maxHeapsort.cpp b/maxHeapsort.cpp new file mode 100644 index 0000000..8d67c99 --- /dev/null +++ b/maxHeapsort.cpp @@ -0,0 +1,73 @@ +#include +#include +using namespace std; + +void heapify(vector &arr, int n, int i) +{ + int largest = i; + int l = 2*i + 1; + int r = 2*i + 2; + + // if left child is larger than root + if (l < n && arr[l] > arr[largest]) + largest = l; + + // if right child is larger than largest so far + if (r < n && arr[r] > arr[largest]) + largest = r; + + // if largest is not root + if (largest != i) + { + swap(arr[i], arr[largest]); + + // recursively heapify the affected sub-tree + heapify(arr, n, largest); + } +} + +void heapSort(vector &arr, int n) +{ + // build heap (rearrange array) + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); + + // one by one extract an element from heap + for (int i=n-1; i>=0; i--) + { + // move current root to end + swap(arr[0], arr[i]); + + // call max heapify on the reduced heap + heapify(arr, i, 0); + } +} + +/* function to print array of size n */ +void printArray(vector &arr, int n) +{ + for (int i = 0; i < n; i++) + { + cout << arr[i] << " "; + } + cout << "\n"; +} + + +int main() +{ + vector v; + int n; + cout<<"Enter Size Of Array:"; + cin>>n; + for(int i=0;i>x; + v.push_back(x); + } + heapSort(v, n); + + cout << "Sorted array is \n"; + printArray(v, n); +} diff --git a/mergesort.cpp b/mergesort.cpp new file mode 100644 index 0000000..8932342 --- /dev/null +++ b/mergesort.cpp @@ -0,0 +1,47 @@ +#include +using namespace std; + +int mrg_sort(int arr1[],int n1,int arr2[],int n2,int result[]){ + int i,j,k; + i=j=k=0; + while(i< n1 && j arr2[j]) + result[k++] = arr2[j++]; + else + { + result[k++]=arr1[i++]; + j++; + } + } + if(i>arr1[i]; + cout<<"\nEnter 10 numbers [arr2]: "; + for(i=0;i<10;i++) + cin>>arr2[i]; + + int item=mrg_sort(arr1,10,arr2,10,result); + cout<<"\n\nAfter sort : "; + for(i=0;i