c++ STL---selectionSort

使用c++的模板函数库中的库函数,外加自己书写的辅助函数进行选择排序的测试。

可以自己创建一个.h文件,文件中书写自己可能用的到的方法,在此我书写了随机产生0~10000之间随机数和打印输出的模板函数的.h文件,来帮助我完成selectionSort函数的测试。

//SortTestHelper.h file

//宏定义 
#ifndef SELECTIONSORT_SORTTESTHELPER_H
#define SELECTIONSORT_SORTTESTHELPER_H

#include <iostream>
#include <ctime>
#include <cassert>
using namespace std;

namespace SortTestHelper{
    //生成有n个元素的随机数组,每个元素的随机范围为[rangeL,rangeR] 
    int* generateRandomArray(int n,int rangeL,int rangeR){
        assert(rangeL <= rangeR);//保证左边界值小于右边界值的库函数
        int *arr = new int[n];
        srand(time(NULL));  //随机种子的设置
        for(int i = 0; i < n; i++){
            arr[i] = rand() % (rangeR - rangeL + 1) + rangeL;  //为数组元素使用随机数赋值
        }
        return arr;//返回函数名
    }
    
    template<typename T>//输出模板函数
    void printArr(T arr[],int n){
        for(int i = 0; i < n; i++)
            cout << arr[i] << " ";
        cout << endl;
        return;
    }
}
#endif //SELECTIONSORT_SORTTESTHELPER_H
//test program    the 
#include <iostream> 
#include "SortTestHelper.h"  //reference the file of .h
using namespace std;

void swap(int *xp,int *yp)  //a fuction to swap the numbers
{
    int tmp;
    tmp = *xp;
    *xp = *yp;
    *yp = tmp; 
}

void selectionSort(int a[],int n)// the function to the selectionSort
{//寻找[i,n)区间里的最小值 
    int minIndex;
    
    for(int i = 0; i < n-1; i++){
        minIndex = i;
        for(int j = i + 1; j < n; j++){
            if(a[j] < a[minIndex])  //find the minimum of the unsort array
                minIndex = j;
        }
        swap(&a[i],&a[minIndex]);   //swap the numbers
    }

}
//driver program
int main()
{
    int n = 10000;
    int *arr = SortTestHelper::generateRandomArray(n,0,n);   //reference the file of .h
    selectionSort(arr,n);//selectionSort to sort the array 
    SortTestHelper::printArr(arr,n);//print out the elements of the array
    delete[] arr;  //free the space that was  ever distributed to the array
    return 0;
}

You can leave me a message if you find out any mistake in my diary, I'll correct it, thanks.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AI阅读 16,041评论 3 119
  • 【01】 总觉得,每个人在某个瞬间都会感觉自己无能为力,那些难熬的艰难的日子,没有任何人能够去感同身受,到最后,只...
    一澜曈河阅读 5,399评论 0 2
  • 春天还没来的时候 都在嘲笑是瞎胡闹,瞎折腾。 但我不认为坚持这条路是错的。 自己走的路, 过程是否开心快乐,或痛苦...
    随心随新阅读 1,046评论 0 4
  • 人生就像是一片海洋,随风飘 忽,只有自己好好理清思路才能好好 的走下一部的时间,很多都是徒劳罢 了,没有谁...
    YKYK阅读 1,196评论 0 0