本文包含:
取随机数(random函数)
快速排序(qSort函数)
快速排序的优化 - 数量少的时候使用插入排序,尾递归优化(qSort1函数)
插入排序 - 0位置使用"哨兵"小技巧提高效率(insertSort函数)
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <math.h>
#include <vector>
#include <sstream>
#include <list>
#include <algorithm>
#include <time.h>
//头文件引用的较多,有一些和本程序无关
using namespace std;
//取随机数
int random(int min = 1, int max = 100);
//分割,交换记录(可以合到qSort函数中,只是为了看着方便才单独写一个函数)
int partition(int arr[], int low, int high);
//排序
void qSort(int arr[], int low, int high);
//优化排序,低于指定个数的排序使用插入排序
void qSort1(int arr[], int low, int high);
//插入排序
//感觉这样优化没什么必要,少量数据排序虽然理论上插入算法更好一些,但实际上差别不大
void insertSort(int arr[]);
//自动生成等排序数组的个数
const int NUM = 50;
//优化,低于此个数的排序使用插入排序,有资料认为7最合理,也有资料说是50
const int MAX_LENGTH_INSERT_SORT = 7;
int main(int argc, char *argv[])
{
srand(((int)time(0)));
//也可用其他的数据形式,如链表...
int arr[NUM+1];//网上学的小技巧,arr[0]位置用作哨兵,插入排序用到这个哨兵了
for(int i = 1; i < NUM + 1; i++)//随机取100个数,在[1-100]之间(有可能重复)
arr[i] = random();
cout << "排序前:" << arr[1];
for(int i = 2; i < NUM + 1; i++)
cout << ", " << arr[i];
cout << endl << endl;
//qSort(arr, 1, NUM);
qSort1(arr, 1, NUM);
cout << "排序后:" << arr[1];
for(int i = 2; i < NUM + 1; i++)
cout << ", " << arr[i];
cout << endl;
system("pause");
return 0;
}
int random(int min, int max)
{
//srand(((int)time(0))); //随机种子 写在这不好使,不知道为什么
//return min + (rand() % (max - min + 1));
return min + (max - min + 1) * rand() / RAND_MAX;//也可以这么写
}
//分割,交换记录
int partition(int arr[], int low, int high)
{
int pivot = 0;//中心点
//优化,左中右三数取中
{
int m = low + (high - low) / 2;
if(arr[low] > arr[high])
swap(arr[low], arr[high]); //左右比较保证左端较小
if(arr[m] > arr[high])
swap(arr[m], arr[high]); //中右比较保证中间较小
if(arr[m] > arr[low])
swap(arr[m], arr[low]); //左中比较保证中间较小,左端为三数的中间值
}
pivot = arr[low];
while(low < high)
{
while(low < high && arr[high] >= pivot)
high--;
arr[low] = arr[high];
//swap(arr[low++], arr[high]);
while(low < high && arr[low] <= pivot)
low++;
arr[high] = arr[low];
//swap(arr[low], arr[high--]);
}
arr[low] = pivot;//如果之前使用swap交换,就不用这句了
return low;
}
//排序
void qSort(int arr[], int low, int high)
{
int pivot = 0;
if(low < high)
{
pivot = partition(arr, low, high);
//递归
qSort(arr, low, pivot - 1);
qSort(arr, pivot + 1, high);
}
}
//优化排序,低于指定个数的排序使用插入排序
void qSort1(int arr[], int low, int high)
{
int pivot = 0;
if(high - low > MAX_LENGTH_INSERT_SORT)
{
while(low < high)
{
pivot = partition(arr, low, high);
//递归
qSort1(arr, low, pivot - 1);
low = pivot + 1;//尾递归优化
}
}
else
insertSort(arr);
}
//插入排序
//感觉这样优化没什么必要,少量数据排序虽然理论上插入算法更好一些,但实际上差别不大
void insertSort(int arr[])
{
int i, j;
for(i = 1; i < NUM; i++)
{
if(arr[i] < arr[i-1])
{
arr[0] = arr[i];//设置哨兵
for(j = i - 1; arr[j] > arr[0]; j--)
arr[j+1] = arr[j];//记录后移
arr[j+1] = arr[0];//插入到正确位置
}
}
}
运行结果: