简体   繁体   中英

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>

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. So if you switch the if block after the j loop ends, the code should work.

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;
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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