Bubble sorting

Bubble sort, sometimes incorrectly referred to as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort. Although the algorithm is simple, most other algorithms are more efficient for sorting large lists.



Bubble sort algorithm in c


  1. #include    int main() {
    int array[100], n, c, d, swap; printf("Enter number of elements\n");
    scanf("%d", &n);
    printf("Enter %d integers\n", n);
    for (c = 0; c < n; c++)
    scanf("%d", &array[c]);
    for (c = 0 ; c < ( n - 1 ); c++)
    {
    for (d = 0 ; d < n - c - 1; d++)
    {
    if (array[d] > array[d+1]) /* For decreasing order use < */
    {
    swap = array[d];
    array[d] = array[d+1];
    array[d+1] = swap;
    }
    }
    }
    printf("Sorted list in ascending order:\n");
    for ( c = 0 ; c < n ; c++ )
    printf("%d\n", array[c]);
    return 0; }

Class Sorting algorithm
Data structure Array
Worst case performance O(n^2)
Best case performance O(n)
Average case performance O(n^2)
Worst case space complexity O(1) auxiliary

Bubble sort in c language using function

  1. #include    void bubble_sort(long [], long);   int main() {
    long array[100], n, c, d, swap;
    printf("Enter number of elements\n");
    scanf("%ld", &n);
    printf("Enter %ld longegers\n", n);
    for (c = 0; c < n; c++)
    scanf("%ld", &array[c]);
    bubble_sort(array, n);
    printf("Sorted list in ascending order:\n");
    for ( c = 0 ; c < n ; c++ )
    printf("%ld\n", array[c]);
    return 0; } void bubble_sort(long list[], long n) {
    long c, d, t;
    for (c = 0 ; c < ( n - 1 ); c++)
    {
    for (d = 0 ; d < n - c - 1; d++)
    {
    if (list[d] > list[d+1])
    {
    /* Swapping */
    t= list[d];
    list[d] = list[d+1];
    list[d+1] = t;
    }
    }
    } }

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post