Posted By

attomos on 11/27/10


Tagged

os lab


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

cdnicoll


sort.c


 / Published in: C
 

  1. #include <stdio.h>
  2.  
  3. void swap(int *x, int *y) {
  4. int temp;
  5. temp = *x;
  6. *x = *y;
  7. *y = temp;
  8. }
  9.  
  10. void selectionSort(int list[], int n) {
  11. int i, j, min;
  12.  
  13. for (i = 0; i < n - 1; i++) {
  14. min = i;
  15. for (j = i + 1; j < n; j++) {
  16. if (list[j] < list[min]) {
  17. min = j;
  18. }
  19. }
  20. swap(&list[i], &list[min]);
  21. }
  22. }
  23.  
  24. void printList(int list[], int n) {
  25. int i;
  26. for (i = 0; i < n; i++) {
  27. if (i < n - 1)
  28. printf("%d, ", list[i]);
  29. else
  30. printf("%d\n", list[i]);
  31. }
  32. }
  33.  
  34. void main() {
  35. const int MAX = 30;
  36. int list[MAX];
  37. int i;
  38. i = 0;
  39. for (i = 0; i < MAX; i++) {
  40. scanf("%d", &list[i]);
  41.  
  42. }
  43. // print the input
  44. printf("The elements in array before sort\n");
  45. printList(list, MAX);
  46. // sort an array
  47. selectionSort(list, MAX);
  48. // print the output
  49. printf("The elements in array after sort\n");
  50. printList(list, MAX);
  51. }

Report this snippet  

You need to login to post a comment.