Skip to content

Instantly share code, notes, and snippets.

@vinitshahdeo
Last active September 1, 2018 13:21
Show Gist options
  • Save vinitshahdeo/2f13e09a50f105b412b0990e2d5a1a62 to your computer and use it in GitHub Desktop.
Save vinitshahdeo/2f13e09a50f105b412b0990e2d5a1a62 to your computer and use it in GitHub Desktop.
Sorting Algorithms
/*
Author - Vinit Shahdeo
Check here - https://code.hackerearth.com/ad6725j
*/
#include <iostream>
using namespace std;
void printArray(int a[],int n)
{
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
}
void merge(int a[],int l,int m,int r)
{
int n1=m-l+1;
int n2=r-m;
int L[n1],R[n2];
for(int i=0;i<n1;i++)
{
L[i]=a[l+i];
}
for(int j=0;j<n2;j++)
{
R[j]=a[m+1+j];
}
int i=0,j=0,k=l;
while(i<n1 && j<n2)
{
if(L[i]<=R[j])
{
a[k]=L[i];
i++;
}
else
{
a[k]=R[j];
j++;
}
k++;
}
while(i<n1)
{
a[k]=L[i];
i++;
k++;
}
while(j<n2)
{
a[k]=R[j];
j++;
k++;
}
}
void mergeSort(int a[],int l,int r)
{
if(l<r)
{
int m=(l+r)/2;
mergeSort(a,l,m);
mergeSort(a,m+1,r);
merge(a,l,m,r);
}
}
int main()
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
mergeSort(a,0,n-1);
cout<<"\n Array after sorting : ";
printArray(a,n);
cout<<endl;
return 0;
}
#include <bits/stdc++.h>
using namespace std;
vector<string> split_string(string);
// Complete the minimumSwaps function below.
// minimum swaps in selection sort
int minimumSwaps(vector<int> arr) {
int min_index;
int count=0;
for(int i=0;i<arr.size()-1;i++)
{
min_index=i;
for(int j=i+1;j<arr.size();j++)
{
if(arr[min_index]>arr[j])
min_index=j;
}
if(min_index!=i)
{
count++;
swap(arr[i],arr[min_index]);
}
}
for(int i=0;i<arr.size();i++)
cout<<arr[i]<<" ";
return count;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int n;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string arr_temp_temp;
getline(cin, arr_temp_temp);
vector<string> arr_temp = split_string(arr_temp_temp);
vector<int> arr(n);
for (int i = 0; i < n; i++) {
int arr_item = stoi(arr_temp[i]);
arr[i] = arr_item;
}
int res = minimumSwaps(arr);
fout << res << "\n";
fout.close();
return 0;
}
vector<string> split_string(string input_string) {
string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
return x == y and x == ' ';
});
input_string.erase(new_end, input_string.end());
while (input_string[input_string.length() - 1] == ' ') {
input_string.pop_back();
}
vector<string> splits;
char delimiter = ' ';
size_t i = 0;
size_t pos = input_string.find(delimiter);
while (pos != string::npos) {
splits.push_back(input_string.substr(i, pos - i));
i = pos + 1;
pos = input_string.find(delimiter, i);
}
splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));
return splits;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment