所有的排序都以升序为例。考虑复杂度,考虑稳定性的情况。以及在原基础上步步优化。
在上篇排序(1)的博客里有提到过稳定性的问题。但是没有做出解释。在这边解释一下稳定性的问题。
排序前:5,1,3a,,4,7,3b
稳定的排序:1,3a,3b,4,5,7
不稳定的排序:1,3b,3a,4,5,7
在自定义的对象进行排序的时,稳定性会影响最终的排序效果。
加粗样式
选择排序:
算法:
**1.在序列中找出最大的那个元素,然后与末尾的元素进行交换。(执行完一轮后,最末尾的那个元素就是最大元素);
**2.忽略1中曾经找到的那个最大元素,重复执行步骤1.
选择排序:
void SelectSort::sort(int array[], int len)
{
if (array == NULL || len == 1)
{
return;
}
this->m_array = array;
this->m_len = len;
for (int end = this->m_len - 1; end > 0; end--)
{
//每次假设数组的首元素为数组序列的最大值
int maxIndex = 0;
for (int begin = 1; begin <= end; begin++)
{
//如果序列中有maxIndex大的元素,maxIndex变化
if(this->cmp(maxIndex,begin) <= 0)
{
maxIndex = begin;
}
}
//最大的元素与数组最后一个元素交换,end随之在for里面--
this->swap(maxIndex, end);
}
for (int i = 0; i < this->m_len; i++)
{
cout << this->m_array[i] << "_";
}
}
选择排序的优化:
其实堆排序就是对选择排序的优化,在后面的博客中会详细介绍堆排序。