The basic idea of bubble sort is to pass through the file sequentially several times. Each pass consists of comparing each element in the file with its successor(x[i] with x[i+1]) and interchanging the two elements if they are not in proper order.
Below is the working procedure code.
void BubbleSort(int x[], int n)
{
int tmp,i,j;
int switched = 1;
for(i=0;i<n-1 && switched==1;i++)
{
/* idea of using switched variable is if there
* is no interchanging of element in one complete
* array iteration means array is sorted .
*/
switched = 0;
for(j=0;j<n-i-1;j++)
if(x[j]>x[j+1])
{
switched = 1;
tmp = x[j];
x[j] = x[j+1];
x[j+1] = tmp;
}
}
}
The above procedure will sort the array in ascending order.
Consider the elements of array are
25 57 48 37 12
Here we will see the state of array after each iteration.
iteration 0 25 57 48 37 12
iteration 1 25 37 48 12 57
iteration 2 25 37 12 48 57
iteration 3 25 12 37 48 57
iteration 4 12 25 37 48 57
Time complexity of bubble sort in average case is O(n2). But in case if the file is already sorted time complexity of this sort will be O(n).
Below is the working procedure code.
void BubbleSort(int x[], int n)
{
int tmp,i,j;
int switched = 1;
for(i=0;i<n-1 && switched==1;i++)
{
/* idea of using switched variable is if there
* is no interchanging of element in one complete
* array iteration means array is sorted .
*/
switched = 0;
for(j=0;j<n-i-1;j++)
if(x[j]>x[j+1])
{
switched = 1;
tmp = x[j];
x[j] = x[j+1];
x[j+1] = tmp;
}
}
}
The above procedure will sort the array in ascending order.
Consider the elements of array are
25 57 48 37 12
Here we will see the state of array after each iteration.
iteration 0 25 57 48 37 12
iteration 1 25 37 48 12 57
iteration 2 25 37 12 48 57
iteration 3 25 12 37 48 57
iteration 4 12 25 37 48 57
Time complexity of bubble sort in average case is O(n2). But in case if the file is already sorted time complexity of this sort will be O(n).
No comments:
Post a Comment