#include
#include
using namespace std;
void print(int *a) { int k; for (k = 0; k < 10; k++) cout << a[k] << " "; cout << endl; }
void shellinsert(int *a, int n, int d) //间隔d进行排序
{
for (int i = d; i < n; i++) //第d+1个数
{
int x = a[i]; //记录
int j = i;
while (j >= d&&x < a[j - d]) //如第i-d个数比较,如果大于,就不用排了直接插入;如果小于,a[j-d]后移,继续往前找,直到在合适的地方插入;
{
a[j] = a[j - d];
j = j - d;
}
a[j] = x;//插入
print(a);
}
}
void shell(int* a, int n) //shell插入排序
{
int d = n/2;
while (d>=1)
{
shellinsert(a, n, d);
print(a);
d /= 2;
}
}
void main()
{
int a[] = { 49,38,65,97,76,13,24,49,55,04 };
print(a);
shell(a, 10); //shell排序
shellinsert(a, 10, 1); //d=1时的shell插入就是简单的插入排序
}#include
#include
using namespace std;
const int N = 10;
void print(int *a) { int k; for (k = 0; k < N; k++) cout << a[k] << " "; cout << endl; }
void heapadjust(int *a, int location, int length) //调整堆
{
int child = 2 * location + 1;
while (child
a[location])//如果孩子更大 { int temp = a[child]; a[child] = a[location]; a[location] = temp; //交换child和location的元素 } else break;//如果爸爸更大,就不用调整了 location = child; //下移 child = 2 * child + 1; } } void buildheap(int *a, int length) //建立堆 { int i = (length - 1) / 2;//最后一个有孩子的节点开始,调整堆 for (i; i >=0; i--) // { heapadjust(a,i, length); } } void heapsort(int* a, int length) //堆排序 { buildheap(a, length);//建立堆 print(a); while (length>0) { int temp = a[0]; a[0] = a[length - 1]; a[length - 1] = temp; //将堆顶元素删除,移动到最后 heapadjust(a, 0, --length); print(a); } } void main() { int a[] = { 49,38,65,97,76,13,24,49,55,04 }; print(a); heapsort(a, N); print(a); }
堆排序
最新推荐文章于 2023-12-04 22:34:24 发布