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);
		}
	}
} 
相关推荐
先做个垃圾出来………1 小时前
差分数组(Difference Array)
java·数据结构·算法
hansang_IR1 小时前
【题解】洛谷 P4286 [SHOI2008] 安全的航线 [递归分治]
c++·数学·算法·dfs·题解·向量·点积
乐迪信息1 小时前
乐迪信息:AI摄像机在智慧煤矿人员安全与行为识别中的技术应用
大数据·人工智能·算法·安全·视觉检测
多恩Stone2 小时前
【3DV 进阶-2】Hunyuan3D2.1 训练代码详细理解下-数据读取流程
人工智能·python·算法·3d·aigc
惯导马工3 小时前
【论文导读】IDOL: Inertial Deep Orientation-Estimation and Localization
深度学习·算法
老姜洛克3 小时前
自然语言处理(NLP)之n-gram从原理到实战
算法·nlp
CoovallyAIHub4 小时前
基于YOLO集成模型的无人机多光谱风电部件缺陷检测
深度学习·算法·计算机视觉
CoovallyAIHub4 小时前
几十个像素的小目标,为何难倒无人机?LCW-YOLO让无人机小目标检测不再卡顿
深度学习·算法·计算机视觉
怀旧,4 小时前
【C++】19. 封装红⿊树实现set和map
linux·c++·算法
往事随风去4 小时前
Redis的内存淘汰策略(Eviction Policies)有哪些?
redis·后端·算法