C Program to Sort an Array Using Selection Sort



In this program, we will implement selection sort algorithm



  1. // C program to sort an array using Selection Sort
  2. #include <stdio.h>
  3. int main()
  4. {
  5. int arr[100], n, i, j, position, swap;
  6. printf("Enter number of elements: ");
  7. scanf("%d", &n);
  8. printf("Enter elements: ");
  9. for (i = 0; i < n; i++)
  10. {
  11. scanf("%d", &arr[i]);
  12. }
  13. for (i = 0; i < (n - 1); i++)
  14. {
  15. position = i;
  16. for (j = i + 1; j < n; j++)
  17. {
  18. if (arr[position] > arr[j])
  19. position = j;
  20. }
  21. if (position != i)
  22. {
  23. swap = arr[i];
  24. arr[i] = arr[position];
  25. arr[position] = swap;
  26. }
  27. }
  28. printf("Sorted array: ");
  29. for (i = 0; i < n; i++)
  30. {
  31. printf("%d ", arr[i]);
  32. }
  33. return 0;
  34. }

Output


Output!