交换排序
基本思想:两两比较,如果发生逆序则交换,直到所有记录都排好序为止。
1. 冒泡排序法
-
基本思想
每趟不断将相邻的两个元素进行比较,逆序的交换元素,每趟结束后,最大的元素排序到位。 -
例子
-
代码实现
void bubbleSort(vector &list)
{
for (int i = 1; i < list.size() ;i++)
{
for (int j = 0; j < list.size() - i; j++)
{
if (list[j + 1] < list[j])
{
int temp = list[j + 1];
list[j + 1] = list[j];
list[j] = temp;
}
}
}
}
- 算法分析
时间复杂度:o(n^2) 。
空间复杂度:o(1) 。
2. 快速排序法
-
基本思想
任取一个元素 (如第一个) 为中心值,所有比它小的元素一律左放,比它大的元素一律后放,形成左右两个子表;对各子表重新选择中心元素并依此规则调整,直到每个子表的元素只剩一个。 -
例子
本例选第一个值为中心值(界点)进行比较,比中心值大的往右放,小的往左放。
以第一个界点排序完如下:
第二个界点:
以27为界点,左右两个子表元素各剩一个,排序结束第三个界点:
以76为界点,左边的子表剩两个元素,继续排序,右边的子表剩一个元素,排序结束。第四个界点:
直到每个子表的元素只剩一个,排序结束。
- 代码实现
#include<iostream>
#include<stack>
using namespace std;
//共同部分——进行分子序列,比关键值大的右放,反之左放;返回分界值下标
int Partition(int list[], int low, int high)
{
int key = list[low];
while (low < high)
{
while (low < high&&list[high] >= key)
high--;
list[low] = list[high];
while (low<high&&list[low]<=key)
low++;
list[high] = list[low];
}
list[low] = key;
return low;
}
//递归实现——begin
void quickSort(int list[], int low, int high)
{
if (low < high)
{
int position = Partition(list, low, high);
quickSort(list, low, position - 1);
quickSort(list, position + 1, high);
}
}
//递归实现——end
//栈实现——begin
void quickSort2(int list[],int n,int low,int high)
{
stack<int> s;
s.push(low);
s.push(high);
while (!s.empty())
{
int high = s.top();
s.pop();
int low = s.top();
s.pop();
int index = Partition(list, low, high);//index为分界值下标,函数进行分子序列,比关键值大的右放,反之左放
//左边部分
if (index - 1 > low)
{
s.push(low);
s.push(index - 1);
}
//右边部分
if (index + 1 < high)
{
s.push(index + 1);
s.push(high);
}
}
}
//栈实现——end
int main()
{
int list[8] = { 49,38,65,97,76,13,27,49 };
int n = 8;
int low = 0;
int high = 7;
quickSort(list, low, high);//递归实现
quickSort2(list,n,low,high);//非递归(栈)实现
}
- 算法分析
时间复杂度:O(nlog2(n))。就平均计算时间而言,快速排序是我们所讨论的所有内排序方法中最好的一个。
空间复杂度:O(log2(n))。递归要用到栈空间。
稳定性:不稳定。
快速排序(非递归)参考博客:
https://blog.youkuaiyun.com/alidada_blog/article/details/82724802