排序算法(2)
希尔排序
希尔(Shell)排序又称为缩小增量排序,它是一种插入排序。它是直接插入排序算法的一种威力加强版。该方法因DL.Shell于1959年提出而得名。
#include<iostream>
using namespace std;
int a[10] = { 9,8,7,6,5,4,3,2,1,0 };
void shell_sort(int size)
{
int gap = size >> 1;
int i, key, end;
while (gap > 0)
{
for (i = gap; i < size; i++)
{
key = a[i];
end = i - gap;
while (end >= 0 && key < a[end])
{
a[end + gap] = a[end];
end -= gap;
}
a[end + gap] = key;
}
gap >>= 1;
}
}
int main()
{
shell_sort(10);
for (int i = 0; i < 10; i++)
{
cout << a[i] << ' ';
}
cout << endl;
system("pause");
return 0;
}
选择排序
算法描述:在未排序的序列中找到最小的元素,存放到序列的首位置,找到最大的元素存放到序列的末尾.然后抛开首位和末尾,继续重复该步骤,直到排完为止.
#include<iostream>
using namespace std;
int a[10] = { 9,8,7,6,5,4,3,2,1,0 };
void selection_sort(int size)
{
int left = 0;
int right = size - 1;
int i;
while (left < right)
{
int MAX = right;
int MIN = left;
for (i = left; i <= right; i++)
{
if (a[MAX] < a[i])
MAX = i;
if (a[MIN] > a[i])
MIN = i;
}
int temp = a[MAX];
a[MAX] = a[right];
a[right] = temp;
if (MIN == right)
MIN = MAX;
temp = a[MIN];
a[MIN] = a[left];
a[left] = temp;
left++;
right--;
}
}
int main()
{
selection_sort(10);
for (int i = 0; i < 10; i++)
{
cout << a[i] << ' ';
}
cout << endl;
system("pause");
return 0;
}
堆排序
运用了二叉树思想
算法描述:若升序的话,就将堆调成一个大堆,若降序的话,就将堆调成一个小堆.从倒数第一个非叶子节点开始往根遍历,若当前节点的值都大于左右孩子,则不用动,若是小于,就将左右孩子当中最大的节点与当前节点交换,交换后就需要进行向下调整(因为交换会影响大堆结构).重复上述步骤,直到根节点为止.
#include<iostream>
using namespace std;
int a[10] = { 9,8,7,6,5,4,3,2,1,0 };
void HeapAdjust(int size, int parent)
{
int child = parent * 2 + 1;
while (child < size)
{
if (child + 1 < size&&a[child + 1] > a[child])
child++;
if (a[child] > a[parent])
{
int temp = a[child];
a[child] = a[parent];
a[parent] = temp;
parent = child;
child = parent * 2 + 1;
}
else
return;
}
}
void HeapSort(int size)
{
int root = (size - 2) >> 1;
int end = size - 1;
for (; root >= 0; root--)
{
HeapAdjust(size, root);
}
while (end)
{
int temp = a[0];
a[0] = a[end];
a[end] = temp;
HeapAdjust(end, 0);
end--;
}
}
int main()
{
HeapSort(10);
for (int i = 0; i < 10; i++)
{
cout << a[i] << ' ';
}
cout << endl;
system("pause");
return 0;
}