排序算法--选择排序

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

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--;
    }
}
相关推荐
郝学胜-神的一滴18 小时前
Effective STL 条款 07:指针容器销毁前先删除
开发语言·c++·vscode·leetcode·rpc·visual studio
Lucas. Wáng21 小时前
Qt学习之旅
c++·qt
星恒随风21 小时前
从0实现C++ AI大模型接入SDK(二):AI知识科普——从图灵测试到ChatGPT,人工智能的发展历程
linux·c++·人工智能·笔记·chatgpt
青少儿编程课堂1 天前
蓝桥杯真题解析:三维偏序的CDQ分治(全国青少年信息素养大赛与电子学会编程考级)
c++·python·算法·bfs·信息学竞赛
Navigator_Z1 天前
LeetCode //C - 1323. Maximum 69 Number
c语言·算法·leetcode
geovindu1 天前
python:Lasso
开发语言·后端·python·算法
AAA修煤气灶刘哥1 天前
同一个模型,为什么还要专门练一遍怎么用工具?
人工智能·后端·算法
csdn_aspnet1 天前
C++ 求给定点集的简单闭合路径(Find Simple Closed Path for a given set of points)
c++
艾莉丝努力练剑1 天前
【AI接入大模型SDK】解决接口连接异常问题
前端·c++·人工智能·学习·ai·架构
Severus_black1 天前
【C++初阶】模板进阶
c语言·c++·学习