#include "stdafx.h"
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
void InsertSort(int *a, int n);
void ShellInsertSort(int *a, int n, int d);
void ShellSort(int *a, int n);
void SelectSort(int *a, int n);
void AdjustHeap(int *a, int start, int end);
void BuildHeap(int *a, int n);
void HeapSort(int *a, int n);
int Partition(int *a, int start, int end);
void QuickSort(int *a, int start, int end);
int main(int argc, char *argv[])
{
int n, *a;
cout << "please input the size of the array" << endl;
cin >> n;
a = (int*)malloc((n + 1)*sizeof(int));
cout << "input the " << n << " number " << endl;
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
QuickSort(a, 0, n - 1);
cout << "after sort " << endl;
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
system("pause");
}
void InsertSort(int *a, int n)
{
int j;
int x;
for (int i = 1; i < n; i++)
{
if (a[i] < a[i - 1])
{
j = i - 1;
x = a[i];
while (j >= 0 && a[j] > x)
{
a[j + 1] = a[j];
j--;
}
a[j + 1] = x;
}
}
}
void ShellSort(int *a, int n)
{
int d = n / 2;
while (d != 0)
{
ShellInsertSort(a, n, d);
d /= 2;
}
}
void ShellInsertSort(int *a, int n, int d)
{
int x, j;
for (int i = d; i < n; i++)
{
if (a[i] < a[i - d])
{
x = a[i];
j = i - d;
while (j >= 0 && a[j]>x)
{
a[j + d] = a[j];
j -= d;
}
a[j + d] = x;
}
}
}
void SelectSort(int *a, int n)
{
int minindex, temp;
for (int i = 0; i < n - 1; i++)
{
minindex = i;
for (int j = i + 1; j < n; j++)
{
if (a[j] < a[minindex])
minindex = j;
}
if (minindex != i)
{
temp = a[minindex];
a[minindex] = a[i];
a[i] = temp;
}
}
}
void HeapSort(int *a, int n)
{
int temp;
BuildHeap(a, n);
for (int i = n - 1; i > 0; i--)
{
temp = a[0];
a[0] = a[i];
a[i] = temp;
AdjustHeap(a, 0, i);
}
}
void BuildHeap(int *a, int n)
{
for (int i = (n-2)/2; i >= 0; i++)
{
AdjustHeap(a, i, n);
}
}
void AdjustHeap(int *a, int start, int end)
{
int child, temp,f;
f = start;
temp = a[f];
child = 2 * f + 1;
while (child < end)
{
if (child + 1 < end&&a[child] < a[child + 1])
child++;
if (a[child] > temp)
{
a[f] = a[child];
f = child;
child = 2 * f + 1;
}
else
break;
}
a[f] = temp;
}
void QuickSort(int *a, int start, int end)
{
if (end > start)
{
int partition = Partition(a, start, end);
QuickSort(a, start, partition - 1);
QuickSort(a, partition + 1, end);
}
}
int Partition(int *a, int start, int end)
{
int temp = a[start];
while (start < end)
{
while (start < end&&a[end] >= temp) end--;
if (start < end) a[start] = a[end];
while (start < end&&a[start] <= temp)start++;
if (start < end)a[end] = a[start];
}
a[start] = temp;
return start;
}