算法思想:
遍历数组,每次遍历寻找未排序部分最小值,与未排序部分首个元素交换,n个元素需要遍历n次。
与插入排序不同的是,选择排序的比较次数与数组的初始状态无关。共需比较 n-1 + n-2 + n-3 + ... + 1 = n(n-1)/2次,时间复杂度为O(n²)
/*************************************************************************
> File Name: selection.c
> Author:zhangji
> Mail:mrzhangji@outlook.com
> Created Time: Mon 02 Oct 2023 06:06:52 PM CST
************************************************************************/
#include "selection.h"
//每次遍历未排序数组,把最小的与未排序首个数据交换,初始状态已排序为空。
void selection_sort(int arr[], int length){
for(int i = 0; i < length;i++){
int min = i;
for(int j = i + 1; j < length; j++){
if(arr[j] < arr[min]) min = j;
}
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}