Register | Sing In

New posts

Stacks in C programming Linked Lists in C programming File Input/Output in C programming Check prime numbers in C Programming C Programming Enumeration C Programming Union

Archives

2013-10 2013-09 2013-08

Selection Sort in C Programming

August 25, 2013 Posted by: GPA Views: 562 0 comments

Problem

Write algorithm of selection sort using C.

Solution

Algorithm's steps:

1 - array is divided into two parts - sorted one and unsorted one. At the beginning, sorted part is empty, while unsorted part contains whole array;

2 - find minimal element in the unsorted part and adds it to the end of the sorted on;

3 - if unsorted part is empty, algorithm stops. 

Let's see an example of sorting an array in the example below. 


Example:

 

   

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
     int A[8] = {5, 1, 12, -5, 16, 2, 12, 14};
     int size=8;
     int i,j,k;
     printf( "Array before Selection sorting:\n" );
     for ( i = 0; i < size; i++ ) {
        printf( "%d ",A[i]);
     }
     int temp;
     int counterformove=0;
     for(i=0;i<size;i++){
         for(j=i+1;j<size;j++){
              if(A[i]>A[j]){
                 temp=A[i];
                 A[i]=A[j];
                 A[j]=temp;
                 counterformove++;
                if(counterformove>1){
                     printf("\nArray after move #%d: ",counterformove-1);
                        for (k = 0; k < size; k++){
                           printf("%d ",A[k]);
                         } 

                  }  
            }
        }
    }
     //show result after sorting
    printf("\n\nArray after Selection sorting:\n" );
     for ( i = 0; i < size; i++ ) {
        printf( "%d ",A[i]);
  }
     printf("\n");
     system("PAUSE");
    return 0;
}

Output

Selection Sort example

Download this example

0 Comments...

Leave a Reply

Please, Sing In to leave a Reply for this material.



Online Chat

LiveZilla Live Help

Popular posts

Function strtok in C programming Check prime numbers in C Programming C Programming Union Linked Lists in C programming File Input/Output in C programming C Programming Enumeration

RSS-subscribe

New materials

Subscribe