|
| 1 | +/* |
| 2 | + * Algorithm: [Bubble Sort] |
| 3 | + * Description: [It starts from the beginning of the list and compares each |
| 4 | + * pair of adjacent elements, and swap them if they are in the |
| 5 | + * wrong order] |
| 6 | + * Time Complexity : |
| 7 | + * Best Case : O(n) // when given array is already sorted. |
| 8 | + * Average Case : O(n^2) //when given array is in random order |
| 9 | + * Worst Case : O(n^2) // when given array is in reverse order |
| 10 | + * Space Complexity: |
| 11 | + * Worst : 0(1) |
| 12 | + * Author: [tanshen-kun] |
| 13 | + */ |
| 14 | + |
| 15 | +#include <stdio.h> |
| 16 | + |
| 17 | +/* |
| 18 | + * bubble_sort : it takse the array and its size then it starts to travel array |
| 19 | + * while comparing successive pairs of element until the travel reach the last |
| 20 | + * element |
| 21 | + * @param arr: Array to process |
| 22 | + * @param size: Size of the array |
| 23 | + * @return: None |
| 24 | + */ |
| 25 | + |
| 26 | +void bubble_sort(int arr[], int size) { |
| 27 | + for (int i = 0; i < size - 1; i++) { |
| 28 | + for (int j = 0; j < size - i - 1; j++) { |
| 29 | + if (arr[j] > arr[j + 1]) { |
| 30 | + int temp = arr[j]; |
| 31 | + arr[j] = arr[j + 1]; |
| 32 | + arr[j + 1] = temp; |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +/* |
| 39 | + * printArray: Prints a given array |
| 40 | + * |
| 41 | + *@param arr: Array to print |
| 42 | + *@param size: Size of the array |
| 43 | + */ |
| 44 | +void printArray(int arr[], int size) { |
| 45 | + for (int i = 0; i < size; i++) { |
| 46 | + printf("%d ", arr[i]); |
| 47 | + } |
| 48 | + printf("\n"); |
| 49 | +} |
| 50 | + |
| 51 | +void test_algorithm() { |
| 52 | + printf("Testing Algorithm...\n"); |
| 53 | + |
| 54 | + // Test Case 1 : Already Sorted |
| 55 | + int test_arr1[] = {1, 2, 3, 4, 5}; |
| 56 | + int size1 = sizeof(test_arr1) / sizeof(test_arr1[0]); |
| 57 | + printf("Test 1 : "); |
| 58 | + bubble_sort(test_arr1, size1); |
| 59 | + printArray(test_arr1, size1); |
| 60 | + |
| 61 | + // Test Case 2 : Random order |
| 62 | + int test_arr2[] = {3, 1, 5, 2, 4}; |
| 63 | + int size2 = sizeof(test_arr2) / sizeof(test_arr2[0]); |
| 64 | + printf("Test 2 : "); |
| 65 | + bubble_sort(test_arr2, size2); |
| 66 | + printArray(test_arr2, size2); |
| 67 | + |
| 68 | + // Test Case 3 : Reverse Order |
| 69 | + int test_arr3[] = {5, 4, 3, 2, 1}; |
| 70 | + int size3 = sizeof(test_arr3) / sizeof(test_arr3[0]); |
| 71 | + printf("Test 3 : "); |
| 72 | + bubble_sort(test_arr3, size3); |
| 73 | + printArray(test_arr3, size3); |
| 74 | +} |
| 75 | + |
| 76 | +int main() { |
| 77 | + test_algorithm(); |
| 78 | + return 0; |
| 79 | +} |
0 commit comments