fork download
  1. // C program for implementation of selection sort
  2. #include <stdio.h>
  3.  
  4. void swap(int* xp, int* yp)
  5. {
  6. int temp = *xp;
  7. *xp = *yp;
  8. *yp = temp;
  9. }
  10.  
  11. void selectionSort(int arr[], int n)
  12. {
  13. int i, j, min_idx;
  14.  
  15. // One by one move boundary of unsorted subarray
  16. for (i = 0; i < n - 1; i++) {
  17. // Find the minimum element in unsorted array
  18. min_idx = i;
  19. for (j = i + 1; j < n; j++)
  20. if (arr[j] < arr[min_idx])
  21. min_idx = j;
  22.  
  23. // Swap the found minimum element with the first
  24. // element
  25. swap(&arr[min_idx], &arr[i]);
  26. }
  27. }
  28.  
  29. /* Function to print an array */
  30. void printArray(int arr[], int size)
  31. {
  32. int i;
  33. for (i = 0; i < size; i++)
  34. printf("%d ", arr[i]);
  35. printf("\n");
  36. }
  37.  
  38. // Driver program to test above functions
  39. int main()
  40. {
  41. int arr[] = { 64, 25, 12, 22, 11 };
  42. int n = sizeof(arr) / sizeof(arr[0]);
  43. selectionSort(arr, n);
  44. printf("Sorted array: \n");
  45. printArray(arr, n);
  46. return 0;
  47. }
  48.  
Success #stdin #stdout 0s 5304KB
stdin
1
457
1
87
1
320
2
3
4
stdout
Sorted array: 
11 12 22 25 64