BenTibnam

Bubble Sort in C

Oct 10th, 2021
678
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2.  
  3. int main()
  4. {
  5.     // Creating a test data set and getting the size of that unsorted array
  6.     int data[] = {1, 4, 7, 2, 9, 0, 8, 5, 6, 3};
  7.     int dataSetSize = sizeof(data) / sizeof(int);
  8.    
  9.     // Keep track of which number we're sorting
  10.     int sortedCount = 0;
  11.  
  12.     while (sortedCount < dataSetSize)
  13.     {
  14.         // we need to check only up to the start of confirmed sorted numbers
  15.         for (int i = 0; i < (dataSetSize - sortedCount) - 1; i++)
  16.         {
  17.             // Two values we have to compare
  18.             int left = data[i];
  19.             int right = data[i + 1];
  20.  
  21.             // Swap unsorted values
  22.             if (left > right)
  23.             {
  24.                 int oldRight = right;
  25.                 data[i + 1] = left;
  26.                 data[i] = oldRight;
  27.             }
  28.            
  29.         }
  30.  
  31.         sortedCount++;
  32.     }
  33.  
  34.     // printing out the final set to show that it's sorted
  35.     for (int i = 0; i < dataSetSize; i++)
  36.     {
  37.         printf("%d\n", data[i]);
  38.     }
  39. }
RAW Paste Data