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);
		}
	}
} 
相关推荐
甄心爱学习17 分钟前
数据挖掘11-分类的高级方法
人工智能·算法·分类·数据挖掘
爪哇部落算法小助手1 小时前
每日两题day44
算法
不穿格子的程序员2 小时前
从零开始写算法——二分-搜索二维矩阵
线性代数·算法·leetcode·矩阵·二分查找
Kuo-Teng3 小时前
LeetCode 19: Remove Nth Node From End of List
java·数据结构·算法·leetcode·链表·职场和发展·list
Kuo-Teng3 小时前
LeetCode 21: Merge Two Sorted Lists
java·算法·leetcode·链表·职场和发展
2301_800399723 小时前
stm32 printf重定向到USART
java·stm32·算法
顾安r4 小时前
11.15 脚本算法 加密网页
服务器·算法·flask·html·同态加密
前端小L4 小时前
图论专题(四):DFS的“回溯”之舞——探寻「所有可能路径」
算法·深度优先·图论
司铭鸿4 小时前
数学图论的艺术:解码最小公倍数图中的连通奥秘
运维·开发语言·算法·游戏·图论
元亓亓亓5 小时前
LeetCode热题100--39. 组合总和
算法·leetcode·职场和发展