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);
		}
	}
} 
相关推荐
Wendy_robot19 分钟前
【滑动窗口+哈希表/数组记录】Leetcode 438. 找到字符串中所有字母异位词
c++·算法·leetcode
程序员-King.25 分钟前
day49—双指针+贪心—验证回文串(LeetCode-680)
算法·leetcode·贪心算法·双指针
转基因1 小时前
Codeforces Round 1020 (Div. 3)(题解ABCDEF)
数据结构·c++·算法
我想进大厂2 小时前
图论---Kruskal(稀疏图)
数据结构·c++·算法·图论
@Aurora.2 小时前
数据结构手撕--【二叉树】
数据结构·算法
victd2 小时前
什么是AutoRec?
算法
陈壮实的搬砖日记2 小时前
抛硬币背后的秘密-通俗玩转二项分布
算法
前端 贾公子2 小时前
力扣 83 . 删除排序链表中的重复元素:深入解析与实现
数据结构·算法
Y1nhl2 小时前
力扣hot100_链表(3)_python版本
python·算法·leetcode·链表·职场和发展
oioihoii3 小时前
C++23 中 constexpr 的重要改动
c++·算法·c++23