cross

Selection Sort for CS50

I have been taking CS50 for a while. CS50 is a online introductory course on computer science from Harvard University. I am having a lot of fun doing this course. I have completed some of the psets in this course. Here is my implementation of selection sort algorithm for pset3.

void sort(int values[], int n){
    // TODO: implement an O(n^2) sorting algorithm
    if(n<1){ return; }else if(n==1){ return; }else if(n==2){ if(values[0]>values[1]){
            int tempx = values[0];
            values[0] = values[1];
            values[1] = tempx;
            return;
        }else{
            return;
        }
    }else{
        for(int i=0; i<=n-1; i++){
            int current = values[i];
            int lowest = current;
            int lowestpos = i;
            for(int j=i+1; j<=n-1; j++){
                    if(values[j]<lowest){
                    lowest=values[j];
                    lowestpos = j;
                }
            }
            int temp = values[i];
            values[i] = values[lowestpos];
            values[lowestpos] = temp;
        }
 }

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Advertisement




Tweets

Get Emails