选择排序算法实现思想个人理解

一、选择排序算法个人理解

  • 如果有N个元素需要排序,首先从N个元素中找到最小的那个元素,然后与索引ix=0位置上的元素进行交换(如果没有比原来索引ix=0位置上的元素小就不用交换),接着再从剩下的N-1个元素中找出最小的元素,再与索引ix=1位置上的元素进行交换;之后,再从剩下的N-2个元素中找出最小的元素,再与索引ix=2位置上的元素进行交换,…重复上面的操作,一直到完全排序完成为止。具体排序过程见下图:
    选择排序算法实现思想个人理解_第1张图片

二、选择排序算法代码实现(C++版本)

#include "iostream"

using namespace std;

void printSequence(int a[], int size);
void selectSort(int a[], int size);

/*        选择排序      */
int main(){
    const int SIZE = 7;
    int a[SIZE] = {5, 7, 2, 8, 9, 1, 4};
    cout << "选择排序前: ";
    printSequence(a, SIZE);

    selectSort(a, SIZE);

    cout << "选择排序后: ";
    printSequence(a, SIZE);
    return 0;
}


void printSequence(int a[], int size){
    for (int i = 0; i <= size - 1; i++){
        cout << a[i] << " ";
    }
    cout << endl;
}

// 选择排序
void selectSort(int a[], int size){
    int minIndex, temp;
    for (int ix = 0; ix < size - 1; ix++){  // 通过外层for循环对索引进行遍历,保存最小元素所对应的索引
        minIndex = ix; // 外层for循环开始循环时,将minIndex初始化为数组第一个元素的索引
        for (int jx = ix + 1; jx < size; jx++){ // 通过内层for循环找出最小元素,并把最小元素所对应的索引赋值给minIndex
            if (a[jx] < a[minIndex])
                minIndex = jx;
        }
        temp = a[ix];
        a[ix] = a[minIndex];
        a[minIndex] = temp;
    }
}
  • STL实现
#include 
#include 
#include 

using namespace std;

// 选择排序思路:
// 1. 在未排序序列中找到最小(大)元素,存放到排序序列的起始位置
// 2. 从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾
// 3. 以此类推,直到所有元素均排序完毕


// 打印元素
void PrintV(vector& v){
    for(auto &e: v){
        cout << e << ' ';
    }
    cout << endl;
}

// 选择排序
void SelectSort(vector& v){
    int n = v.size();
    for(int i=0; i < n-1;++i){
        int min = i;
        for(int j=i+1; j < n; ++j){
            if(v[j] < v[min]){
                min = j;
            }
        }

        if(i != min){
            swap(v[i], v[min]);
        }

    }
}


// 函数模板实现
template 
void SelectSort1(vector& arr){
    int n = arr.size();
    for(int i=0; i < n-1; ++i){
        int min = i;
        for(int j=i+1; j < n; ++j){
            if(arr[j] < arr[min]){
                min = j;
            }
        }

        if(i != min){
            swap(arr[i], arr[min]);
        }
    }
}


int main(){
    vector v{7, 30, 16, 4, 1, 2, 9};
    cout << "选择排序前: ";
    PrintV(v);
    SelectSort(v);
    cout << "选择排序后: ";
    PrintV(v);
    return 0;
}

三、结果

选择排序算法实现思想个人理解_第2张图片

四、选择排序时间复杂度总结:

  • 平均时间复杂度:O(n**2)
  • 最好情况:O(n**2)
  • 最坏情况:O(n**2)
  • 空间复杂度:O(1)
  • 稳定性:不稳定

你可能感兴趣的:(数据结构与算法)