📜  buble sort c (1)

📅  最后修改于: 2023-12-03 15:13:43.658000             🧑  作者: Mango

Buble Sort in C

Buble sort, also known as sinking sort, is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted.

Buble sort has a time complexity of O(n^2) which makes it inefficient for larger datasets but it is a good algorithm to use for small datasets or when space is limited.

Code

The following is an implementation of buble sort in C:

void bubbleSort(int arr[], int n) 
{ 
    int i, j; 
    for (i = 0; i < n-1; i++) 
      
    // Last i elements are already sorted 
    for (j = 0; j < n-i-1; j++) 
        if (arr[j] > arr[j+1]) 
            swap(&arr[j], &arr[j+1]); 
} 

Note: The swap function is not shown in the code above but it is a common utility function used in sorting algorithms and can be easily implemented.

Working

The bubbleSort function takes an array, arr, of integers and the array size, n, as inputs. The function then performs a double loop where the outer loop runs from i = 0 to i < n-1 and the inner loop runs from j = 0 to j < n-i-1.

During each iteration of the inner loop, adjacent elements are compared and if they are in the wrong order, they are swapped. This process is repeated until all elements are in the correct order.

Conclusion

Buble sort is a simple and easy-to-implement sorting algorithm. However, due to its time complexity of O(n^2), it is not suitable for large datasets. Nonetheless, it is still a valuable algorithm to know and should be considered when dealing with small datasets or space-limited situations.