Sorting Algorithm: Bubble Sort
Sorting Algorithm: Bubble Sort
Bubble Sort
Bubble Sort
In this technique we sort the given elements
in ascending and descending order by
comparing two adjacent elements at a time
and placing them in correct position.
If we have n elements then it requires (n-1)
pass to sort.
Example
Consider an array arr having 5 elements
5 4 3 1 2
4 4 5 3 3 3
3 3 3 5 1 1
1 1 1 1 5 2
2 2 2 2 2 5
3 3 4 1 1
1 1 1 4 2
2 2 2 2 4
5 5 5 5 5
1 1 3 2
2 2 2 3
4 4 4 4
5 5 5 5
3
All the elements are sorted in ascending order
3
at the end of Pass 4
4 4
5 5
//function declaration
void bubbleSort(int *a, int n);
int main(){
//variable declaration
int arr[5], i;
//input
for(i = 0; i < 5; i++)
scanf("%d", &arr[i]);
//sort
bubbleSort(arr,5); //sending arr address and no. of elements
//output
for(i = 0; i < 5; i++)
printf("%d\n", arr[i]);
return 0;
}
//function definition
void bubbleSort(int *a, int n){
int k, j, temp;
for(k = 1; k <= n-1; k++){
for(j = 0; j <= n-k-1; j++){
if(a[j] > a[j+1]){
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}