Advertisement
tampurus

2.1 Bubble Sort

Jan 1st, 2022
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.90 KB | None | 0 0
  1. /*
  2. Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
  3. Time complexity is O(n^2) , and in best case it is O(n), if the array is already sorted.
  4. */
  5. #include <stdio.h>
  6. int main()
  7. {
  8.     int n, arr[100];
  9.     printf("Enter the number and elements of array with spaces ");
  10.     scanf("%d", &n);
  11.     for (int i = 0; i < n; i++)
  12.         scanf("%d", &arr[i]);
  13.     for (int i = 0; i < n - 1; i++)
  14.     {
  15.         int flag = 0;
  16.         for (int j = 0; j < n - i - 1; j++)
  17.         {
  18.             if (arr[j] > arr[j + 1])
  19.             {
  20.                 int temp = arr[j + 1];
  21.                 arr[j + 1] = arr[j];
  22.                 arr[j] = temp;
  23.                 flag = 1;
  24.             }
  25.         }
  26.         if (!flag)
  27.             break;
  28.     }
  29.  
  30.     for (int i = 0; i < n; i++)
  31.     {
  32.         printf("%d ", arr[i]);
  33.     }
  34.     return 0;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement