1、选择排序的思想:
原理:我们看到是从第一个开始,选出最小的数据元素,后面以此类推,直至最后全部排序完毕。
#ifndef SORT_H
#define SORT_H
#include "Object.h"
namespace XiebsLib
{
class Sort : public Object
{
private:
Sort();
Sort(const Sort&);
Sort& operator=(const Sort&);
template <typename T>
static void Swap(T& a, T& b)
{
T c = a;
a = b;
b = c;
}
public:
template<typename T>
static void Select(T array[], int len, bool min2max = true)
{
for(int i = 0; i < len; i++)
{
int min = i;
for(int j = i + 1; j < len; j++)
{
if(min2max ? (array[min] > array[j]) : (array[i] < array[j]))
{
min = j; //直接Swap 会每比较一次就调用一次Swap函数,所以这里直接比较得到下标的最小值,下面只比较一次,效率高。
}
}
if(min != i)
{
Swap(array[i],array[min]); //如果最后三个元素就是从小到大排列,min = i,这时候还会调用Swap函数一次,让自身和自身交换,为了避免这样的无意义操作,加上这个条件
}
}
}
};
}
#endif // SORT_H
#include <iostream>
#include "Sort.h"
using namespace std;
using namespace XiebsLib;
int main()
{
int array[] = {3, 2, 4, 1, 5};
Sort::Select(array, 5);
for(int i=0; i<5; i++)
{
cout << array[i] << endl;
}
}
通过上面的排序可知,在排完序后,数据元素的位置已经改动。因此,选择排序是不稳定排序。
2、插入排序的思想:
#ifndef SORT_H
#define SORT_H
#include "Object.h"
namespace XiebsLib
{
class Sort : public Object
{
private:
Sort();
Sort(const Sort&);
Sort& operator=(const Sort&);
template <typename T>
static void Swap(T& a, T& b)
{
T c = a;
a = b;
b = c;
}
public:
template<typename T>
static void Select(T array[], int len, bool min2max = true)
{
for(int i = 0; i < len; i++)
{
int min = i;
for(int j = i + 1; j < len; j++)
{
if(min2max ? (array[min] > array[j]) : (array[i] < array[j]))
{
min = j;
}
}
if(min != i)
{
Swap(array[i],array[min]);
}
}
}
template < typename T >
static void insert(T array[], int len, bool min2max = true)
{
for(int i = 1; i < len; i++)
{
int k = i;
T e = array[i];
for(int j = i-1; (j >= 0) && (min2max ? array[j] > e : array[j] < e); j--)
{
array[j+1] = array[j]; //比它大的元素都后移一位
k = j;
}
if(i != k)
{
array[k] = e;
}
}
}
}
#endif // SORT_H
#include <iostream>
#include "Sort.h"
using namespace std;
using namespace XiebsLib;
int main()
{
int array[] = {3, 2, 4, 1, 5};
Sort::insert(array, 5);
for(int i=0; i<5; i++)
{
cout << array[i] << endl;
}
}
- 小结:
1、选择排序每次选择未排元素中的最小元素,插入排序每次将第 i 个元素插入前面 i-1 个已排元素中;
2、选择排序是不稳定的排序法,插入排序是稳定的排序方法;
3、选择排序和插入排序的时间复杂度为 O(n2)。