#include<iostream>
using namespace std;
int getkey(int* a, int left, int right)
{
return (right + left) / 2;
}
int sort(int* a, int left, int right)
{
int key = getkey(a, left, right);
int d = a[key];
a[key] = a[left];
a[left] = d;
key = left;
while (left < right)
{
while (left < right && a[right] >= a[key])
{
right--;
}
while (left < right && a[left] < a[key])
{
left++;
}
if (left < right)
{
int e = a[left];
a[left] = a[right];
a[right] = e;
}
}
int f = a[key];
a[key] = a[left];
a[left] = f;
return left;
}
void fast(int* a, int left, int right)
{
if (left >= right)
{
return;
}
int key = sort(a, left, right);
fast(a, left, key - 1);
fast(a, key + 1, right);
}
int main()
{
int a[5] = { 1,5,3,2,4 };
fast(a, 0, 4);
for (int i = 0; i < 5; i++)
{
printf("%d", a[i]);
}
return 0;
}
#include <iostream>
using namespace std;
typedef struct heap {
int* a;
int size;
int capacity;
} hp;
void init(hp* heap, int capacity) {
heap->a = new int[capacity];
heap->size = 0;
heap->capacity = capacity;
}
void swap(int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}
void heapifyDown(hp* heap, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < heap->size && heap->a[left] > heap->a[largest]) {
largest = left;
}
if (right < heap->size && heap->a[right] > heap->a[largest]) {
largest = right;
}
if (largest != i) {
swap(&heap->a[i], &heap->a[largest]);
heapifyDown(heap, largest);
}
}
void buildHeap(hp* heap) {
heap->size = heap->capacity;
for (int i = heap->size / 2 - 1; i >= 0; --i) {
heapifyDown(heap, i);
}
}
void heapSort(int* a, int n) {
hp heap;
init(&heap, n);
for (int i = 0; i < n; ++i) {
heap.a[i] = a[i];
}
heap.size = n;
buildHeap(&heap);
for (int i = heap.size - 1; i >= 0; --i) {
swap(&heap.a[0], &heap.a[i]);
heap.size--;
heapifyDown(&heap, 0);
}
for (int i = 0; i < n; ++i) {
a[i] = heap.a[i];
}
}
int main() {
int a[] = { 15, 3, 2, 4 };
int n = sizeof(a) / sizeof(a[0]);
cout << "Original array: ";
for (int i = 0; i < n; ++i) {
cout << a[i] << " ";
}
cout << endl;
heapSort(a, n);
cout << "Sorted array: ";
for (int i = 0; i < n; ++i) {
cout << a[i] << " ";
}
cout << endl;
return 0;
}