c++ STL---selectionSort

使用c++的模板函數(shù)庫中的庫函數(shù),外加自己書寫的輔助函數(shù)進(jìn)行選擇排序的測(cè)試。

可以自己創(chuàng)建一個(gè).h文件,文件中書寫自己可能用的到的方法,在此我書寫了隨機(jī)產(chǎn)生0~10000之間隨機(jī)數(shù)和打印輸出的模板函數(shù)的.h文件,來幫助我完成selectionSort函數(shù)的測(cè)試。

//SortTestHelper.h file

//宏定義 
#ifndef SELECTIONSORT_SORTTESTHELPER_H
#define SELECTIONSORT_SORTTESTHELPER_H

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

namespace SortTestHelper{
    //生成有n個(gè)元素的隨機(jī)數(shù)組,每個(gè)元素的隨機(jī)范圍為[rangeL,rangeR] 
    int* generateRandomArray(int n,int rangeL,int rangeR){
        assert(rangeL <= rangeR);//保證左邊界值小于右邊界值的庫函數(shù)
        int *arr = new int[n];
        srand(time(NULL));  //隨機(jī)種子的設(shè)置
        for(int i = 0; i < n; i++){
            arr[i] = rand() % (rangeR - rangeL + 1) + rangeL;  //為數(shù)組元素使用隨機(jī)數(shù)賦值
        }
        return arr;//返回函數(shù)名
    }
    
    template<typename T>//輸出模板函數(shù)
    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)區(qū)間里的最小值 
    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.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1、通過CocoaPods安裝項(xiàng)目名稱項(xiàng)目信息 AFNetworking網(wǎng)絡(luò)請(qǐng)求組件 FMDB本地?cái)?shù)據(jù)庫組件 SD...
    陽明AI閱讀 16,175評(píng)論 3 119
  • 【01】 總覺得,每個(gè)人在某個(gè)瞬間都會(huì)感覺自己無能為力,那些難熬的艱難的日子,沒有任何人能夠去感同身受,到最后,只...
    一瀾曈河閱讀 1,616評(píng)論 0 2
  • 春天還沒來的時(shí)候 都在嘲笑是瞎胡鬧,瞎折騰。 但我不認(rèn)為堅(jiān)持這條路是錯(cuò)的。 自己走的路, 過程是否開心快樂,或痛苦...
    隨心隨新閱讀 170評(píng)論 0 4
  • 人生就像是一片海洋,隨風(fēng)飄 忽,只有自己好好理清思路才能好好 的走下一部的時(shí)間,很多都是徒勞罷 了,沒有誰...
    YKYK閱讀 194評(píng)論 0 0

友情鏈接更多精彩內(nèi)容