Advertisement
BenTibnam

Selection Sort in C

Aug 22nd, 2021
1,206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.35 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. const int ARR_SIZE = 10;
  4.  
  5. int main(void)
  6. {
  7.     int arr[] = {1, 2, 5, 3, 4, 7, 6, 10, 8, 9};
  8.  
  9.     // Displaying data pre-selection sort
  10.     printf("PRE SORT\n");
  11.     for (int i = 0; i < ARR_SIZE; i++)
  12.     {
  13.         printf("%i\n", arr[i]);
  14.     }
  15.  
  16.     // Sorting array via selection sort
  17.     for (int i = 0; i < ARR_SIZE-1; i++)
  18.     {
  19.         // Setting current smallest values to the next number in the array
  20.         int smallestNumber = arr[i];
  21.         int smallIndex = i;
  22.  
  23.         // finding the smallest number out of the remaining array
  24.         for (int j = i; j < ARR_SIZE; j++)
  25.         {
  26.             // set location and value variables of the smallest number if something smaller was found in the array
  27.             if (smallestNumber > arr[j])
  28.             {
  29.                 smallestNumber = arr[j];
  30.                 smallIndex = j;
  31.             }
  32.         }
  33.  
  34.         // if the current number isn't the smallest number found set values
  35.         if (arr[i] != smallestNumber)
  36.         {
  37.             int tempHold = arr[i];
  38.             arr[i] = smallestNumber;
  39.             arr[smallIndex] = tempHold;
  40.             smallestNumber = arr[i+1];
  41.         }
  42.  
  43.     }
  44.  
  45.     // Displaying data post-selection sort
  46.     printf("\nPOST SORT\n");
  47.  
  48.     for (int i = 0; i < ARR_SIZE; i++)
  49.     {
  50.         printf("%i\n", arr[i]);
  51.     }
  52.  
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement