6-1 选择排序

cpp 复制代码
#include <stdio.h>

#define N 1000
int arr[N];

/* 对长度为n的数组arr执行选择排序 */
void selectionSort(int arr[], int n);

/* 打印长度为n的数组arr */
void printArray(int arr[], int n);

void swap(int *xp, int *yp) {
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}

int main() {
    int n, i;
    scanf("%d", &n);
    for (i = 0; i < n; ++i) {
        scanf("%d", &arr[i]);
    }
    selectionSort(arr, n);
    printArray(arr, n);
    return 0;
}
/* 打印长度为n的数组arr */
void printArray(int arr[], int n) {
    int i;
    for (i = 0; i < n; i++) {
        printf("%d", arr[i]);
        if (i < n - 1)  /* 下标0..n-2每个元素后面有个空格 */
            printf(" ");/*下标n-1,也就是最后一个元素后面没有空格*/
    }
    printf("\n");/* 一行打印完后换行 */
}

/* 你的代码将嵌在这里 */

输入样例:

10

1 19 9 11 4 3 5 8 10 6

输出样例:

1 3 4 5 6 8 9 10 11 19

solution

c 复制代码
void selectionSort(int arr[], int n){
	for(int i = 0; i < n; i++){
		for(int j = i + 1; j < n; j++){
			if(arr[i] > arr[j]) swap(arr + i, arr + j);
		}
	}
} 
相关推荐
北顾笙98029 分钟前
day38-数据结构力扣
数据结构·算法·leetcode
m0_6294947331 分钟前
LeetCode 热题 100-----14.合并区间
数据结构·算法·leetcode
xin_nai35 分钟前
LeetCode热题100(Java)(5)普通数组
算法·leetcode·职场和发展
旖-旎1 小时前
深搜练习(组合)(5)
c++·算法·深度优先·力扣
@小码农1 小时前
2026年3月Scratch图形化编程等级考试一级真题试卷
开发语言·数据结构·c++·算法
Wect2 小时前
LeetCode 5. 最长回文子串:DP + 中心扩展
前端·算法·typescript
糖果店的幽灵2 小时前
决策树详解与sklearn实战
算法·决策树·sklearn
Lewiis2 小时前
趣谈排序算法
算法·排序算法
ComputerInBook2 小时前
数字图像处理(4版)——第 8 章——图像压缩与水印(上)(Rafael C.Gonzalez&Richard E. Woods)
人工智能·算法·计算机视觉·图像压缩·图像水印
刀法如飞2 小时前
Python列表去重:从新手三连到高阶特技,20种解法全收录
python·算法·编程语言