Sorting Algorithms are concepts that every competitive programmer must know. Sorting algorithms can be used for collections of numbers, strings, characters, or a structure of any of these types.
Bubble sort is based on the idea of repeatedly comparing pairs of adjacent elements and then swapping their positions if they exist in the wrong order.
Assume that  is an unsorted array of  elements. This array needs to be sorted in ascending order. The pseudo code is as follows:
void bubble_sort( int A[ ], int n ) {
    int temp;
    for(int k = 0; k< n-1; k++) {
        // (n-k-1) is for ignoring comparisons of elements which have already been compared in earlier iterations
        for(int i = 0; i < n-k-1; i++) {
            if(A[ i ] > A[ i+1] ) {
                // here swapping of positions is being done.
                temp = A[ i ];
                A[ i ] = A[ i+1 ];
                A[ i + 1] = temp;
            }
        }
    }
}
Lets try to understand the pseudo code with an example: 
A [ ] = { 7, 4, 5, 2}
In step 1,  is compared with . Since ,  is moved ahead of . Since all the other elements are of a lesser value than ,  is moved to the end of the array.
Now the array is .
In step 2,  is compared with . Since  and both  and  are in ascending order, these elements are not swapped. However, when  is compared with ,  and these elements are in descending order. Therefore, and  are swapped.
Now the array is .
In step 3, the element  is compared with . Since  and the elements are in descending order,  and  are swapped.
The sorted array is .
Complexity:
The complexity of bubble sort is in both worst and average cases, because the entire array needs to be iterated for every element.
The complexity of bubble sort is in both worst and average cases, because the entire array needs to be iterated for every element.
Không có nhận xét nào:
Đăng nhận xét