简体   繁体   English

在 C 语言中为什么我的选择排序代码不起作用

[英]In C language why my selection-sort code doesn't work

I wrote a selection-sort algorithm but didn't work.我写了一个选择排序算法,但没有用。 I cannot find my wrong.我找不到我的错。 Anyone can help me ?任何人都可以帮助我吗?

#include <stdio.h> #include <stdio.h>

int main () {
    
    int array[100],i,j,position,size,swap;
    
    printf("Enter number of integers\n");
    scanf("%d",&size);
    printf("Enter %d integers\n",size);
    for(i=0;i<size;i++){
        scanf("%d",&array[i]);
    }
    
    for(i=0;i<size;i++){
        position=i;
            for(j=i;j<size;j++){
                if(array[position]>array[j]){
                    position=j;
                    
                }
                if(position!=i){
                    swap=array[i];
                    array[i]=array[position];
                    array[position]=swap;
                }
            }   
    }
    printf("Sorted list in ascending order\n");
    for(i=0;i<size;i++){
        printf("%d\n",array[i]);
    }
    
    return 0;
}

The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the beginning.选择排序算法通过从未排序部分重复查找最小元素(考虑升序)并将其放在开头来对数组进行排序。

So the swap needs to happen after you have found the correct position ie happening after your for loop is over.所以交换需要在你找到正确的位置之后发生,即在你的 for 循环结束之后发生。 So if you switch the if block after the j loop ends, the code should work.因此,如果在 j 循环结束后切换 if 块,代码应该可以工作。

for(i=0;i<size;i++){
position=i;
    for(j=i;j<size;j++){
        if(array[position]>array[j]){
            position=j;
        }
    }  
    if(position!=i){
            swap=array[i];
            array[i]=array[position];
            array[position]=swap;
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM