排序算法--选择排序

选择排序虽然简单,但时间复杂度较高,适合小规模数据或教学演示。

cpp 复制代码
// 选择排序函数
void selectionSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) { // 外层循环控制当前最小值的存放位置
        int minIndex = i; // 假设当前位置是最小值的索引

        // 内层循环查找未排序部分的最小值
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j; // 更新最小值的索引
            }
        }

        // 将找到的最小值与当前位置交换
        if (minIndex != i) {
            int temp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
        }
    }
}
cpp 复制代码
#include <stdio.h>
// 打印数组函数
void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int arr[] = {64, 25, 12, 22, 11}; // 待排序数组
    int n = sizeof(arr) / sizeof(arr[0]); // 计算数组长度

    printf("排序前的数组: \n");
    printArray(arr, n);

    selectionSort(arr, n); // 调用选择排序函数

    printf("排序后的数组: \n");
    printArray(arr, n);

    return 0;
}

优化建议

1)减少交换次数:在每轮循环中只记录最小值的索引,最后再交换。

cpp 复制代码
void selectionSortOptimized(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int minIndex = i;
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }
        if (minIndex != i) {
            int temp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
        }
    }
}

2)双向选择排序:同时查找最小值和最大值,减少循环次数。

cpp 复制代码
void bidirectionalSelectionSort(int arr[], int n) {
    int left = 0, right = n - 1;
    while (left < right) {
        int minIndex = left, maxIndex = right;
        for (int i = left; i <= right; i++) {
            if (arr[i] < arr[minIndex]) minIndex = i;
            if (arr[i] > arr[maxIndex]) maxIndex = i;
        }
        if (minIndex != left) {
            int temp = arr[left];
            arr[left] = arr[minIndex];
            arr[minIndex] = temp;
        }
        if (maxIndex == left) maxIndex = minIndex; // 如果最大值在 left,已被交换到 minIndex
        if (maxIndex != right) {
            int temp = arr[right];
            arr[right] = arr[maxIndex];
            arr[maxIndex] = temp;
        }
        left++;
        right--;
    }
}
相关推荐
xianyinsuifeng14 分钟前
Oracle 10g → Oracle 19c 升级后问题解决方案(Pro*C 项目)
c语言·数据库·oracle
方案开发PCBA抄板芯片解密15 分钟前
什么是算法:高效解决问题的逻辑框架
算法
深耕AI19 分钟前
【MFC文档与视图结构:数据“仓库”与“橱窗”的梦幻联动 + 初始化“黑箱”大揭秘!】
c++·mfc
songx_9926 分钟前
leetcode9(跳跃游戏)
数据结构·算法·游戏
学c语言的枫子36 分钟前
数据结构——双向链表
c语言·数据结构·链表
励志不掉头发的内向程序员43 分钟前
STL库——二叉搜索树
开发语言·c++·学习
小白狮ww1 小时前
RStudio 教程:以抑郁量表测评数据分析为例
人工智能·算法·机器学习
AAA修煤气灶刘哥1 小时前
接口又被冲崩了?Sentinel 这 4 种限流算法,帮你守住后端『流量安全阀』
后端·算法·spring cloud
tan180°1 小时前
Boost搜索引擎 查找并去重(3)
linux·c++·后端·搜索引擎
kk”2 小时前
C语言快速排序
数据结构·算法·排序算法