# 希尔、归并排序C++算法实现

``````#include <iostream>

using namespace std;
int arrs[] = { 23, 65, 12, 3, 8, 76, 345, 90, 21, 75, 34, 61 };
int arrLen = sizeof(arrs) / sizeof(arrs[0]);

void shellSort(int * arrs){
int step = arrLen / 2;      //初始增量
while(step > 0){
//无序部分
for(int i = step; i < arrLen; i++){
int temp = arrs[i];
int j;
//子序列中的插入排序,这是有序部分
for(j = i-step; j>=0 && temp < arrs[j]; j=j-step)
//在找到当前元素合适位置前，元素后移
arrs[j+step]=arrs[j];
arrs[j+step]=temp;
}
step /= 2;
}
}

int main()
{
shellSort(arrs);
for (int i = 0; i < arrLen; i++)
cout << arrs[i] << endl;
return 0;
}
``````

``````#include <iostream>

using namespace std;
int arrs[] = { 23, 65, 12, 3, 8, 76, 345, 90, 21, 75, 34, 61 };
int arrLen = sizeof(arrs) / sizeof(arrs[0]);
int * tempArr = new int[arrLen];

void mergeArray(int * arrs, int * tempArr, int left, int middle, int right){
int i = left, j = middle ;
int m = middle + 1, n = right;
int k = 0;

while(i <= j && m <= n){
if(arrs[i] <= arrs[m])
tempArr[k++] = arrs[i++];
else
tempArr[k++] = arrs[m++];
}
while(i <= j)
tempArr[k++] = arrs[i++];
while(m <= n)
tempArr[k++] = arrs[m++];

for(i=0; i < k; i++)
arrs[left + i] = tempArr[i];
}

void mergeSort(int * arrs, int * tempArr, int left, int right){
if(left < right){
int middle = (left + right)/2;
mergeSort(arrs, tempArr, left, middle);
mergeSort(arrs, tempArr, middle + 1, right);
mergeArray(arrs, tempArr, left, middle, right);
}
}

int main()
{
mergeSort(arrs, tempArr, 0, arrLen-1);
for (int i = 0; i < arrLen; i++)
cout << arrs[i] << endl;
return 0;
}
``````