Skip to content

Instantly share code, notes, and snippets.

@gouravbarkle
Created June 9, 2021 02:12
Show Gist options
  • Save gouravbarkle/d4107fe24b14f5875e1b06adbda3d747 to your computer and use it in GitHub Desktop.
Save gouravbarkle/d4107fe24b14f5875e1b06adbda3d747 to your computer and use it in GitHub Desktop.
Sorting
#include<bits/stdc++.h>
using namespace std;
void BubbleSort(vector<int> &v)
{
int len = v.size();
for(int k=0;k<len; k++)
{
bool flag = true;
for(int i=0;i<len-1; i++)
{
if(v[i]>v[i+1])
{
swap(v[i], v[i+1]);
flag = false;
}
}
if(flag)
break;
}
}
void RecursiveBS(vector<int> &v, int i, int j, int& N)
{
if(!N || j> v.size()-1)
return;
if(v[i]> v[j])
swap(v[i], v[j]);
if(j == v.size()-1)
{
N--;
i=-1, j=0;
}
RecursiveBS(v, i+1, j+1, N);
}
int main()
{
vector<int> v;
int n;
cin>>n;
while(n--)
{ int t; cin>>t;
v.push_back(t);
}
cout<<"Before : ";
for(int i: v)
cout<<i<<" ";
// BubbleSort(v);
int N = v.size();
RecursiveBS(v, 0,1, N);
cout<<"\nAfter : ";
for(int i: v)
cout<<i<<" ";
return 0;
}
#include<bits/stdc++.h>
using namespace std;
void selectionSort(vector<int> &v)
{
int len = v.size();
for(int i = 0; i< len; i++)
{
int curMinIndex = i;
for(int j = i+1; j<len; j++)
{
if(v[j]<v[curMinIndex])
curMinIndex = j;
}
swap(v[i], v[curMinIndex]);
}
}
int main()
{
vector<int> v;
int n;
cin>>n;
while(n--)
{ int t; cin>>t;
v.push_back(t);
}
cout<<"Before : ";
for(int i: v)
cout<<i<<" ";
selectionSort(v);
cout<<"\nAfter : ";
for(int i: v)
cout<<i<<" ";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment