首页 > 解决方案 > 选择排序算法 (C)

问题描述

我试图研究一些算法问题,但我找不到开始我的选择排序算法代码的方法。我使用 Visual Studio 并且代码通过编译没有显示任何错误。当我启动代码时,系统会停止几秒钟并打印“按任意键继续...”。我是初学者,我看不出有什么问题。帮助我

#include <stdio.h>

int n = 6;

int qwerty(int a[]) {
    int i, j, t;
    for (i=1; i<=n-1; i++){
        for (j=i+1; j<=n; j++){
            if (a[i] > a[j]){
                t = a[j]; 
                a[j] = a[i]; 
                a[i] = t;
            }
        }
    }
}

int main(void) {
    int a[6] = { 2, 14, 20, 8, 17, 13 };
    qwerty(a[n]);
    int i;
    for (i = 1; i <= n; i++){
        printf("%d ", a[i]);
    }
}

标签: calgorithmsortingselectcompilation

解决方案


In the C language, arrays start indexing at 0, and the last element is at the index n-1. So the first thing you should change is the loops to be for(i = 0; i < n-1; i++) and for(j = i + 1; j < n; j++)

Also, this is a bubble sort algorithm, not selection sort. Selection sort algorithms can be found anywhere so I'm not going to type it here.


推荐阅读