Commit dccf2865 authored by Asal Asgari's avatar Asal Asgari
Browse files

Realized multiset is basically a binary search tree and changed the whole code :)))

parent 691fb4f7
......@@ -4,93 +4,27 @@
// stl
#include <iterator>
#include <algorithm>
#include <set>
namespace dte3603::sort::algorithms
{
template <std::random_access_iterator Iterator_T,
std::random_access_iterator Sentinel_T >
auto next_it(Iterator_T it,Sentinel_T endit,int count){
auto iter = it;
int c = 0;
if (count>0){
for(;iter<endit;++iter){
if (c==count)
break;
c++;
}
}
else{
for(;;iter--){
if (c==count)
break;
c--;
}
}
return iter;
}
template <std::random_access_iterator Iterator_T,
std::random_access_iterator Sentinel_T,
typename Compare_T = std::less<> >
auto binarySearch(Iterator_T begin, Sentinel_T end ,
auto item,auto low, auto high)
{
using Type = typename std::iterator_traits<Iterator_T>::value_type;
if (high<=low){
auto lowtar = next_it(low,end,1);
return (std::less<Type>{}(*(low),item) ?
(lowtar) : low);
}
auto distance = std::distance(low,high);
distance = (distance -1)/2;
auto mid = next_it(low,end ,(int(distance)));
if (std::equal_to<Type>{}(item,*(mid))){
auto midtar = next_it(mid,end,1);
return midtar;
}
if (std::less<Type>{}(*(mid),item))
{
auto midtar = next_it(mid,end,1);
return binarySearch(begin,end, item,
midtar, high);
}
auto midles = next_it(mid,end,-1);
return binarySearch(begin,end,item, low,
midles);
}
template <std::random_access_iterator Iterator_T,
std::random_access_iterator Sentinel_T,
typename Compare_T = std::less<> >
void binary_sort(Iterator_T begin, Sentinel_T end,
Compare_T /*comp*/ = Compare_T())
Compare_T comp = Compare_T())
{
using Type = typename std::iterator_traits<Iterator_T>::value_type;
std::multiset<Type, Compare_T> binarySort(comp);
for (auto i = begin; i != end; ++i) {
binarySort.insert(*i);
}
for(auto i=binarySort.begin();i!=binarySort.end();++i){
*begin = *i;
begin++;
}
auto nSize=std::distance(begin,end);
auto it = next_it(begin,end,1);
for ( ; it != end; ++it)
{
auto j = next_it(it,end,(-1));
auto selected = (*it);
auto loc = binarySearch(begin,end, selected, begin, j);
for(;j>=loc;j--){
auto jPlus = next_it(j,end,1);
*jPlus = *j;
}
auto jPlus = next_it(j,end,1);
*jPlus = selected;
}
}
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment