algorithms

algorithms Commit Details


Date:2013-02-16 22:28:00 (11 years 10 months ago)
Author:Natalie Adams
Branch:default
Commit:5017e17bb2f1
Parents: 17a967c7a5e4
Message:Mediansort does not work

Adding working code for QuickSort
Changes:
Acpp/algorithms/src/QuickSort.h (full)
Mcpp/algorithms/src/MedianSort.h (1 diff)

File differences

cpp/algorithms/src/MedianSort.h
22
33
44
5
56
67
78
8
9
910
1011
1112
1213
13
14
1415
1516
16
17
1718
18
19
20
1921
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
2043
2144
22
45
2346
2447
#define MEDIAN_SORT_H
#include "SortAlgorithm.h"
#include <algorithm>
#include <vector>
template <class T>
class InsertSort : public SortAlgorithm<T>
class MedianSort : public SortAlgorithm<T>
{
public:
virtual void Sort()
{
this->mediansort(this->_container);
this->mediansort(0, this->_container.size());
}
void mediansort(std::vector<T> arr)
void mediansort(size_t left, size_t right)
{
if (arr.size() == 0)
throw exception("Does not work!");
if (left >= right || (right - left) == 1)
return;
//if (arr.size() == 0 || arr.size() == 1 || arr.size() == 2)
//return;
//int midpos = arr.size() / 2;
size_t pivot = right - left -1;
size_t mid = right / 2;
std::swap(this->_container[pivot], this->_container[mid]);
for(size_t i = left; i < mid - 1; i++)
{
if (this->_container.at(i) > this->_container.at(mid))
{
for (size_t k = mid + 1; k < this->_container.size(); k++)
{
if (this->_container.at(k) <= this->_container.at(mid))
{
std::swap(this->_container[i], this->_container[k]);
}
}
}
}
mediansort(left, left+mid-1);
mediansort(left+mid+1, right);
}
}
};
#endif
cpp/algorithms/src/QuickSort.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#ifndef QUICKSORT_H
#define QUICKSORT_H
#include "SortAlgorithm.h"
#include <algorithm>
template <class T>
class QuickSort : public SortAlgorithm<T>
{
public:
virtual void Sort()
{
quicksort(0, this->_container.size() - 1);
}
void quicksort(int left, int right)
{
if (right <= left)
return;
int store;
int pivindex = left + right / 2;
std::swap(this->_container[pivindex], this->_container[right]);
store = left;
for(int i = left; i < right - 1; i++)
{
if (this->_container[i] <= this->_container[right])
{
std::swap(this->_container[i], this->_container[store]);
store++;
}
}
std::swap(this->_container[store], this->_container[right]);
quicksort(left, store - 1);
quicksort(store + 1, right);
}
};
#endif

Archive Download the corresponding diff file

Branches

Tags

Page rendered in 0.40910s using 14 queries.