Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merge_Sort #42

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions merge_sort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
#include<bits/stdc++.h>
using namespace std;


void merge(int arr[],int left,int mid,int right)
{
//number of elements in the divided arrays
int nL=mid-left+1; //nL number of elements in left array
int nR = right-mid; //nR number of elements in right array

int L[nL],R[nR]; //temporary arrays

for(int i=0;i<nL;i++)
{
L[i] = arr[left+i];
}
for(int j=0;j<nR;j++)
{
R[j]=arr[mid+1+j];
}

int i=0,j=0,k=left;

while(i<nL && j<nR)
{
if(L[i]<=R[j])
{
arr[k] = L[i];
i++;
}
else{
arr[k]=R[j];
j++;
}
k++;
}

//copying the remaining elements
while(i<nL)
{
arr[k]=L[i];
i++;
k++;
}

while(i<nR)
{
arr[k]=R[j];
j++;
k++;
}
}

void mergeSort(int arr[],int left,int right)
{
if(left<right)
{
int mid = left + (right-left)/2;
mergeSort(arr,left,mid);
mergeSort(arr,mid+1,right);

//merging the sorted arrays
merge(arr,left,mid,right);
}
}
//printting the array
void printArray(int arr[],int n)
{
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}

int main()
{
int n;
cout<<"Enter the size of array :";
cin>>n;
int arr[n];
cout<<"Enter the elements: ";
for(int i=0;i<n;i++)
{
cin>>arr[i];
}

mergeSort(arr,0,n-1);

cout<<"The sorted Array is: "<<endl;
printArray(arr,n);
return 0;
}
47 changes: 47 additions & 0 deletions priority_queue.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@

//by default priority queue creates max-heap.

#include <bits/stdc++.h>
using namespace std;



void showpq(priority_queue<int>pq)
{
priority_queue<int>p = pq; //just copied it
while(!p.empty())
{
cout<<"\t"<<p.top();
p.pop();
}
cout<<"\n";
}


int main()
{
priority_queue<int>pq;

// we can create a min heap priority queue using the below line
//priority_queue<int,vector<int>,greater<int>>pq;
pq.push(20);
pq.push(40);
pq.push(30);
pq.push(3);
pq.push(1);

cout<<"The priority Queue is: ";
showpq(pq);



return 0;
}