Moved programs to appropriate directories

This commit is contained in:
ashwek
2019-02-12 20:32:46 +05:30
parent bd6c8a3531
commit e946cc8291
10 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,64 @@
//Using general algorithms to sort a collection of strings results in alphanumeric sort.
//If it is a numeric string, it leads to unnatural sorting
//eg, an array of strings 1,10,100,2,20,200,3,30,300
//would be sorted in that same order by using conventional sorting,
//even though we know the correct sorting order is 1,2,3,10,20,30,100,200,300
//This Programme uses a comparator to sort the array in Numerical order instead of Alphanumeric order
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
bool NumericSort(string a,string b)
{
while(a[0]=='0')
{
a.erase(a.begin());
}
while(b[0]=='0')
{
b.erase(b.begin());
}
int n=a.length();
int m=b.length();
if(n==m)
return a<b;
return n<m;
}
int main()
{
int n;
cout << "Enter number of elements to be sorted Numerically\n";
cin >> n;
vector<string> v(n);
cout << "Enter the string of Numbers\n";
for(int i=0;i<n;i++)
{
cin >> v[i];
}
sort(v.begin(),v.end());
cout << "Elements sorted normally \n";
for(int i=0;i<n;i++)
{
cout << v[i] << " ";
}
cout << "\n";
sort(v.begin(),v.end(),NumericSort);
cout << "Elements sorted Numerically \n";
for(int i=0;i<n;i++)
{
cout << v[i] << " ";
}
return 0;
}

51
Sorting/combsort.cpp Normal file
View File

@@ -0,0 +1,51 @@
//Kind of better version of Bubble sort.
//While Bubble sort is comparering adjacent value, Combsort is using gap larger than 1
//Best case: O(n)
//Worst case: O(n ^ 2)
#include <iostream>
using namespace std;
int a[100005];
int n;
int FindNextGap(int x) {
x = (x * 10) / 13;
return max(1, x);
}
void CombSort(int a[], int l, int r) {
//Init gap
int gap = n;
//Initialize swapped as true to make sure that loop runs
bool swapped = true;
//Keep running until gap = 1 or none elements were swapped
while (gap != 1 || swapped) {
//Find next gap
gap = FindNextGap(gap);
swapped = false;
// Compare all elements with current gap
for(int i = l; i <= r - gap; ++i) {
if (a[i] > a[i + gap]) {
swap(a[i], a[i + gap]);
swapped = true;
}
}
}
}
int main() {
cin >> n;
for(int i = 1; i <= n; ++i) cin >> a[i];
CombSort(a, 1, n);
for(int i = 1; i <= n; ++i) cout << a[i] << ' ';
return 0;
}