Selection Sort(选择排序)

来源:互联网 发布:淘宝详情页好做吗 编辑:程序博客网 时间:2024/06/05 11:19

选择排序:从未排好的部分的第一个作为最小(最大)的,然后依次和剩余的比较,如果有更小(更大)的,记下下标,以此作为新的最小(最大)值,继续比较,一趟结束后,然后和第一个进行交换。

核心代码

template<typename T>void selectionSort( T arr[], int n){    for (int i = 0; i < n; i++){        int minIndex = i;        for(int j = i + 1; j < n; j++){            if(arr[j] < arr[minIndex]) minIndex = j;        }        swap( arr[i], arr[minIndex] );    }}

生成随机测试数组

namespace SortTestHelper{    // 生成有n个元素的随机数组,每个元素的随机范围为 [langeL, 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;    }}

测试代码运行时间

namespace SortTestHelper{    template<typename T>    bool isSorted (T arr[], int n){        for (int i = 0; i < n-1; i++){            if(arr[i] > arr[i+1]) return false;        }        return true;    }    template<typename T>    void testSort(string sortName, void(*sort)(T [], int), T arr[], int n){        clock_t startTime = clock();        sort(arr,n);        clock_t endTime = clock();        assert( isSorted(arr,n) );        cout << sortName << ":" << double(endTime - startTime) / CLOCKS_PER_SEC << "s" << endl;        return;    }}

运算符重载

struct Student{    string name;    int score;    bool operator<(const Student &otherStudent){        return score != otherStudent.score ? score < otherStudent.score : name < otherStudent.name;    }    friend ostream& operator<<(ostream &os, const Student &student){        os<<"Student: "<<student.name<<" "<<student.score<<endl;        return os;    }};
原创粉丝点击