快速排序(Quick sort):
- 思想:选一个基准元素,将比该元素小的放在左边,大的放在右边,以此分割,再将分割所得子序列按同样的方式分割,直到原序列有序。
- 优缺点:快、数据移动少、但是不稳定
- 复杂度:平均时间复杂度:O(nlogn)、最好:O(nlogn)、最坏:O(n^2)
空间复杂度:最好:O(logn)、 最坏:O(n) - 稳定性:不稳定
源代码
/****************************************
题目:快速排序。
编写划分函数:以一个随机的数,
将数组分为大于该数的右半边和小于该数的左半边
*****************************************/
#include<ctime> //时间种子
#include<cstdlib> //随机数rand
#include<iostream>
using namespace std;
int Partition(int[], int, int, int); //划分函数的声明【把划分函数提到该函数前面,则不用声明】
//快速排序
//参数:
// data[]:需要划分的数组
// length:数组的长度
// begin:需要划分的开始下标
// end:需要划分的结束下标
void QuickSort(int data[], int length, int begin, int end)
{
if (begin == end)
return;
int index = Partition(data, length, begin, end);
if (index > begin)
QuickSort(data, length, begin, index - 1);
if (index < end)
QuickSort(data, length, index + 1, end);
}
//函数功能:取随机数,范围在[begin,end]闭区间内
int RandomInRange(int begin, int end)
{
srand((unsigned)time(NULL));
return ((rand() % (end - begin + 1)) + begin);
//return (rand() % (end - begin + 1) + 1);
}
//函数功能:交换两数在内存中的位置【不用传递原数据进来,直接传递要交换的两数的地址】
void Swap(int* p1, int* p2)
{
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
//函数功能:以一个随机的数,将数组分为大于该数的右半边和小于该数的左半边
//参数:
// data[]:需要划分的数组
// length:数组的长度
// begin:需要划分的开始下标
// end:需要划分的结束下标
int Partition(int data[], int length, int begin, int end)
{
//1. 判断,传入参数是否不符合规则,不符合则抛出异常
if (data == nullptr || length <= 0 || begin < 0 || end >= length)
throw new exception("Invalid input.");
//2. 随机在范围内取一个下标,指向的数字即为本次划分的分界点
int index = RandomInRange(begin, end);
//3. 将分界点数字放在数组的末尾
Swap(&data[index], &data[end]);
//4. 定义sumallNumsIndex代表比分界点小的数的个数(下标)
int smallNumsIndex = begin - 1;
for (index = begin; index < end; index++)
{
//5. 从头开始遍历,判断数是否比分界点小
if (data[index] < data[end])
{
//6. 如果小,说明找到了第一个在分界点左边的数字,small下标++
++smallNumsIndex;
//7. 判断,如果当前下标和小数下标不同步,
// 说明是隔了几个大数才出现的小数,交换位置,把小数调到前面去
if (smallNumsIndex != index)
Swap(&data[smallNumsIndex], &data[index]);
}
}
//8. 最后,再把分界点换到所有小数的右边
++smallNumsIndex;
Swap(&data[smallNumsIndex], &data[end]);
return smallNumsIndex;
}
//简单测试
int main(int argc, char* argv[])
{
int nums[] = {
4, 5, 1, 7, 5 };
QuickSort(nums, 5, 0, 4);
for (int i = 0; i < 5; i++)
cout << nums[i] << " ";
cout << endl;
return 0;
}
仍有不足,欢迎交流。