This blog is under construction

Saturday 23 February 2013

C Program To Perform Selection Sort

Selection sort is an in-place sorting algorithm and it works as below.

Consider an array of 'n' entries, search for the smallest entry in that array and swap it to the first position.  After that, search the remaining elements(2 to n) to find the next smallest element and swap it to the second position.  Continue this operation until all the elements in the array are sorted.

50   10   40   30   20

10   50   40   30   20

10   20   40   30   50

10   20   30   40   50

See Also:


Example Program For Selection Sort:



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

  int main() {
        int *data, count, temp, i, j, min;
        printf("No of elements:");
        scanf("%d", &count);
        data = (int *)malloc(sizeof (int) * count);
        printf("Enter ur inputs:\n");
        for (i = 0; i < count; i++) {
                scanf("%d", &data[i]);
        }

        /* advance 1 position for each level of parsing */
        for (i = 0; i < count - 1; i++) {
                /* search for the min element */
                min = i;
                for (j = i + 1; j < count; j++) {
                        if (data[j] < data[min]) {
                                min = j;
                        }
                }

                /* swap min element with the current element */
                if (min != i) {
                        temp = data[i];
                        data[i] = data[min];
                        data[min] = temp;
                }
                for (j = 0; j < count; j++)
                        printf("%-3d", data[j]);
                printf("\n");
        }
        printf("Sorted Data:\n");
        for (i = 0; i < count; i++)
                printf("%-3d", data[i]);
        printf("\n");
        return 0;
  }



  Output: (C Program To Implement Selection Sort)
  jp@jp-VirtualBox:$ ./a.out
  No of elements:5
  Enter ur inputs:
  50 10 40 30 20
  10 50 40 30 20 
  10 20 40 30 50 
  10 20 30 40 50 
  Sorted Data:
  10 20 30 40 50




No comments:

Post a Comment