Pagini recente » Cod sursa (job #2028934) | Cod sursa (job #869798) | Cod sursa (job #2862332) | Cod sursa (job #2455416) | Cod sursa (job #946712)
Cod sursa(job #946712)
// QuickSort Implementation
// MergeSort Implementation with n/2 additional memory
// HeapSort Implementation
#include <vector>
#include <algorithm>
#include <stdio.h>
using namespace std;
class MergeSort
{
void join(vector <int> &arrayToSort, int startIndex, int endIndex)
{
int midIndex = (startIndex + endIndex) >> 1;
int length = midIndex - startIndex + 1;
vector <int> auxArray(length);
for (int i = startIndex; i <= midIndex; i++)
auxArray[i - startIndex] = arrayToSort[i];
for (int i = 0, j = midIndex + 1, poz = startIndex; i < length || j <= endIndex; poz++)
if (i >= length || (j <= endIndex && auxArray[i] > arrayToSort[j]))
arrayToSort[poz] = arrayToSort[j++];
else arrayToSort[poz] = auxArray[i++];
}
public:
void sort(vector <int> &arrayToSort, int startIndex, int endIndex)
{
if (startIndex == endIndex)
return;
int midIndex = (startIndex + endIndex) >> 1;
sort(arrayToSort, startIndex, midIndex);
sort(arrayToSort, midIndex + 1, endIndex);
join(arrayToSort, startIndex, endIndex);
}
};
class QuickSort
{
pair <int, int> partition(vector <int> &arrayToSort, int startIndex, int endIndex)
{
for (int pivot = arrayToSort[startIndex]; startIndex < endIndex; )
{
for (; arrayToSort[startIndex] < pivot; startIndex++);
for (; arrayToSort[endIndex] > pivot; endIndex--);
if (startIndex <= endIndex)
{
swap(arrayToSort[startIndex], arrayToSort[endIndex]);
startIndex++;
endIndex--;
}
}
return make_pair(startIndex, endIndex);
}
public:
void sort(vector <int> &arrayToSort, int startIndex, int endIndex)
{
if (startIndex >= endIndex)
return;
pair <int, int> part = partition(arrayToSort, startIndex, endIndex);
sort(arrayToSort, startIndex, part.second);
sort(arrayToSort, part.first, endIndex);
}
};
int main()
{
int n;
scanf("%d", &n);
vector <int> vctSort(n);
for (int i = 0; i < n; i++)
scanf("%d", &vctSort[i]);
MergeSort().sort(vctSort, 0, n - 1);
for (int i = 0; i < n; i++)
printf("%d ", vctSort[i]);
return 0;
}