您的位置:首页 > 编程语言 > C语言/C++

常见排序算法小结一(C++实现)(未完)

2017-08-04 18:50 549 查看

基于比较的排序

插入排序 与 希尔排序

选择排序 与 堆排序

冒泡排序

快速排序(冒泡排序的改进)

归并排序

堆排序

非比较排序

基数排序

桶排序

计数排序

各种排序算法的可视化过程见 visuAlgo

为了对比各个排序算法的性能,实现sort.cpp。

static bool isSorted(int a[],int len) //测试数组元素是否有序

static void time(int a[],int len,sortType alg) //给定输入,对已有排序算法计时

static void sort(int data[],int len, sortType alg) //对使用alg排序方法,对输入进行排序

int * proudct( int length) //产生一个长度为N的数组

main.cpp

#include"sort.cpp"

//产生一个长度为N的数组
int * proudct( int length)
{
const int MaxNum = 1000;//产生随机数的范围
int *tmp = new int[length];

srand((unsigned)time(0));
int ran_num;
for (int i = 0; i < length;i++)
{
ran_num = rand() % MaxNum;
tmp[i] = ran_num;
//cout << ran_num << " ";
}
return tmp;
}

int main()
{
int len = 10000;
int *arr = proudct(len);//产生一个长度为len的数组

Sort::time(arr, len, sortType::BubbleSort);
Sort::isSorted(arr, len);//判断是否有序
system("pause");
return 0;
}


多个排序算法 Sort.cpp 代码如下

#include<iostream>
#include<time.h>

using namespace std;
enum sortType
{
Insertion ,
Selection ,
BubbleSort,
QuickSort,
shellSort,
CountSort,
};

class Sort{
public:
static void sort(int data[],int len, sortType alg)
{
switch (alg)
{
case sortType::Insertion:
Insertion(data, len);break;
case sortType::Selection:
Selection(data, len);break;
case sortType::BubbleSort:
BubbleSort(data, len);break;
case sortType::QuickSort:
QuickSort(data, len);break;
case sortType::shellSort:
shellSort(data, len);break;
default:
break;
}
};

//给定输入,对已有排序算法计时
static void time(int a[],int len,sortType alg)
{
int *arr2 = new int[len];
for (int i = 0; i < len;i++)
arr2[i] = a[i];

time_t time_start = clock();
sort(arr2, len, alg);
time_t time_end = clock();
double cost = double(time_end - time_start);
cout << "耗时:" << cost << "ms"<<endl;
}

//测试数组元素是否有序
bool static isSorted(int a[],int len)
{
for (int i = 0; i < len - 1; i++)
{
if (a[i] > a[i+1])
{
cout << "error:没有正确排序" << endl;
Sort::show(a, len);
cout << a[i] << ">" << a[i+1] << endl;
return false;
}
}
cout << "right:正确排序" << endl;
return true;
}

void static show(int a[], int len)
{
cout << "排序后" << endl;
for (int i = 0; i < len; i++){
cout << a[i] << " ";
}
cout << endl;
}
private:
//1、插入排序
static void Insertion(int data[], int len){}
//2、选择排序
static void Selection(int data[], int len){}
//3、冒泡排序
static void BubbleSort(int data[], int len){}
//4、希尔排序
static void shellSort(int data[], int len){}
//5、快速排序
static void QuickSort(int data[], int len){}
//6、归并排序
static void MergeSort(int data[], int len){}
//7、堆排序
static void HeapSort(int data[], int len){}

//1、计数排序
static void CountSort(int data[], int len){}
//2、桶排序
static void RadixSort(int data[], int len){}
//3、基数排序
static void RadixSort(int data[], int len){}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ 排序算法总结