Bubble sort is the simplest sorting algortihm that works by repeatedly swapping the adjacent elements if they are in wrong order.
Example:
First Pass
( 5 1 4 2 8 ) → ( 1 5 4 2 8 ), algorithm compares the first two elements, and swaps since 5>1
( 1 5 4 2 8 ) → ( 1 4 5 2 8 ), swap since 5>4
( 1 4 5 2 8 ) → ( 1 4 2 5 8 ), swap since 5>2
( 1 4 2 5 8 ) → ( 1 4 2 5 8 ), now, since these elements are already in order (8>5), algorithm does not swap them.
Second Pass
( 1 4 2 5 8 ) → ( 1 4 2 5 8 )
( 1 4 2 5 8 ) → ( 1 2 4 5 8 ), swap since 4>2
( 1 2 4 5 8 ) → ( 1 2 4 5 8 )
( 1 2 4 5 8 ) → ( 1 2 4 5 8 )
Now, the array is already sorted.
void bubbleSort (int arr [], int n)
{
int i,j;
for (i=0; i<n-1; i++)
for (j=0; j<n-i-1; j++)
if (arr[j] > arr[j+1])
swap (&arr[j], &arr[j+1]);
}
Bana ulaşmak için e-posta ve instagram.
Kabarcık Sıralama
Hiç yorum yok:
Yorum Gönder