天天看點

C++泛型冒泡排序代碼

檔案:

// File: bubbleSort.h
#ifndef _BUBBLESORT_H_
#define _BUBBLESORT_H_

template <typename numeric>

void bubbleSort(numeric* arr, int size, int direction = 1) {
    if (!direction)
        return;
    else {
        direction = (direction < 0) ? -1 : 1;
        numeric temp;
        bool changeFlag;
        for (int i = 0; i < size-1; i++) {
            changeFlag = false;
            for (numeric* j = arr; j < arr+size-i-1; j++) {
                if (*j*direction > *(j+1)*direction) {
                    changeFlag = true;
                    temp = *j;
                    *j = *(j+1);
                    *(j+1) = temp;
                }
            }
            if (!changeFlag)
                return;
        }
        return;
    }
}

#endif
           

調用方法:

bubbleSort( 任何數字類型的數組頭, int型數組長 (, int型方向) );

其中可選的參數“方向”規定為:輸入正數時将數組遞增排序,輸入負數時将數組遞減排序,輸入 0 時數組将原封不動(函數直接傳回),預設為 1 即遞增排序。

繼續閱讀