Advertisement
GradleDaemon

Selection

Nov 13th, 2018
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. //Ria Subramanian ap cs50 selection sort
  2. #include <cs50.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <ctype.h>
  7.  
  8. int main(void)
  9. {
  10. //gets size of array from user and creates array
  11. printf("Enter size of your array\n");
  12. int size = get_int();
  13. int array[size];
  14. //gets unsorted array from user
  15. printf("Enter array elements\n");
  16. for(int i = 0; i < size; i++)
  17. {
  18. array[i] = get_int();
  19. }
  20. //sets index of smallest number
  21. int minIndex = 0;
  22. for(int i = 0; i < size - 1; i++)
  23. {
  24. //assumes minimum is i
  25. minIndex = i;
  26. for(int j = i + 1; j < size; j++)
  27. {
  28. //checks for values smaller than array element minIndex
  29. if(array[j] < array[minIndex])
  30. {
  31. minIndex = j;
  32. }
  33. }
  34. //if the minIndex isn't the i value then array[i] and array[minIndex are swapped]
  35. if(minIndex != i)
  36. {
  37. int temp = 0;
  38. int temp2 = 0;
  39. temp = array[minIndex];
  40. for(int j = i; j < size - 1; j++)
  41. {
  42. temp2 = array[j];
  43. array[j] = temp;
  44. temp = temp2;
  45. }
  46. }
  47. }
  48. for(int i = 0; i < size; i++)
  49. {
  50. if(i != size - 1)
  51. {
  52. printf("%i, ", array[i]);
  53. }
  54. else
  55. {
  56. printf("%i", array[i]);
  57. }
  58. }
  59. printf("\n");
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement