# 排序算法

## 直接插入排序

``````void InsertSort(int num[], int n)
{
for(int i=1; i<n; i++){
int v = num[i];
int j = i-1;
for(; j>=0 && num[j]>v; j--){
num[j+1] = num[j];
}
num[j+1] = v;
}
}
``````

``````void BInsertSort(int num[], int n)
{
for(int i=1; i<n; i++){
int v = num[i];
int low = 0;
int high = i-1;
while(low<=high){
int m = (low+high)>>1;
if(num[m]>v){
high = m-1;
}
else{
low = m+1;
}
}
for(int j=i-1; j>=high+1; j--){
num[j+1] = num[j];
}
num[high+1] = v;
}
}
``````

## 希尔排序

``````void ShellSort(int num[], int n)
{
for(int dk=n/2; dk>=1; dk/=2){
for(int i=dk+1; i<n; i++){
int v = num[i];
int j = i-dk;
for(; j>=0 && num[j]>v; j-=dk){
num[j+dk] = num[j];
}
num[j+dk] = v;
}
}
}
``````

## 快速排序

``````int Partition(int num[], int low, int high)
{
int key = num[low];
while(low<high){
while(low<high && num[high]>=key){
high--;
}
num[low] = num[high];
while(low<high && num[low]<=key){
low++;
}
num[high]=num[low];
}
num[low] = key;
return low;
}

void QuickSort(int num[], int low, int high)
{
if(low<high){
int part = Partition(num, low, high);
QuickSort(num, low, part-1);
QuickSort(num, part+1, high);
}
}
``````

## 选择排序

``````void SelectSort(int num[], int n)
{
for(int i=0; i<n; i++){
int pos = i;
for(int j=i+1; j<n; j++){
if(num[pos]>num[j]){
pos = j;
}
}
if(pos != i){
int temp = num[i];
num[i] = num[pos];
num[pos] = temp;
}
}
}
``````

## 堆排序

``````void HeapAdjust(int num[], int s, int m)
{
int key = num[s];
for(int j=2*s; j<m-1; j*=2){
if(j<m-1 && num[j]<num[j+1]){
j++;
}
if(key<num[j]){
num[s] = num[j];
s = j;
}
else{
break;
}
}
num[s] = key;
}

void HeapSort(int num[], int n)
{
for(int i=n/2-1; i>=0; i--){
}
for(int i=n-1; i>0; i--){
int temp = num[0];
num[0] = num[i];
num[i] = temp;
}
}
``````

## 归并排序

``````void Merge(int num[],int temp[], int low, int mid, int high)
{
int i = low;
int j = mid+1;
int k = 0;
while(i<=mid && j<=high){
if(num[i]<=num[j]){
temp[k++] = num[i++];
}
else{
temp[k++] = num[j++];
}
}
while(i<=mid){
temp[k++] = num[i++];
}
while(j<=high){
temp[k++] = num[j++];
}
for(i=0; i<k; i++){
num[low+i] = temp[i];
}
}

void MergeSort(int num[], int temp[], int low, int high)
{
if(low<high){
int mid = (low+high)/2;
MergeSort(num,temp,low,mid);
MergeSort(num,temp,mid+1,high);
Merge(num,temp,low,mid,high);
}
}
``````