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

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

二、选择排序算法代码实现(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;
    }
}

三、结果

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

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

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

相关文章:

  • 2021-09-15
  • 2021-08-21
  • 2021-05-17
  • 2021-05-21
  • 2021-08-28
  • 2022-01-20
  • 2021-11-05
  • 2021-12-27
猜你喜欢
  • 2021-06-28
  • 2022-12-23
  • 2021-08-02
  • 2021-07-06
  • 2021-06-06
  • 2021-05-19
  • 2021-10-28
相关资源
相似解决方案