算法的阶梯

c++ STL---selectionSort

2018-11-01  本文已影响9人  Tedisaname

使用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.

上一篇下一篇

猜你喜欢

热点阅读