BUBBLE SORT
In bubble sorting first and second element is compared, if first number is greater then second then we swap the number, now second number is compared with 3rd if needed it is swapped. This process continues till all elements is swapped.
Lets Take an example:
consider our list is
45, 26, 89, 18, 59, 57
1. First 45 and 26 is compared, it is swapped ( because 45 > 26 )
list is 26, 45, 89, 18, 59, 57
2. Now 45 and 89 is compared, not need to swap.
list is 26, 45, 89, 18, 59, 57
3. Now 89 and 18 is compared , it is swapped ( because 89 > 18 )
list is 26, 45 , 18, 89, 59, 57
4. Now 89 and 59 is compared , it is swapped (because 89 > 59 )
list is 26, 45, 18, 59, 89, 57
5. Now 89 and 57 is compared , it is swapped (because 89 > 57
list is 26, 45, 18, 59, 57, 89
Now our first iteration is over and highest element in list goes to its proper place i.e. last in our case. Again first and second element is compared and swapping is done if needed. So by doing this our complete list is swapped. So our swapping is done in maximum n-1 iteration where n is total number of elements in list
here I show our list at end of each iteration.
1st iteration 26 45 18 59 57 89 2nd iteration 26 18 45 57 59 89 3rd iteration 18 26 45 57 59 89 4th iteration 18 26 45 57 59 89 5th iteration 18 26 45 57 59 89
final sorted list 18 26 45 57 59 89
#include #include void bubble_sort(int [],int); void main() { int i,j,k,temp,arr[20],num,n; clrscr(); cout<<"==========================================\n"; cout<<"\t\tBUBBLE SORT\n"; cout<<"==========================================\n\n"; cout<<"ENTER VALUE OF N:\n"; cin>>n;
for(i=0;i { cout<<"NO("< cin>>arr[i]; } cout<<"\n\t===============================\n"; cout<<"\t\tARRAY BEFORE SORT\n\n\t";
for(i=0;i { cout< } cout<<"\n\t===============================\n"; cout<<"\n\t\tSORTING LOGIC:\n\n"; bubble_sort(arr,n); cout<<"\n\t===============================\n"; cout<<"\t\tSORTED LIST\n\n\t";
for(i=0;i { cout< } getch(); } void bubble_sort(int arr[],int n) { cout<<"\n\n\t"; for(int i=0;i { for(int j=0;j { if(arr[j]>arr[j+1]) { int temp=arr[j+1]; arr[j+1]=arr[j]; arr[j]=temp; } } for(int k=0;k { cout< } cout<<"\n\n\t"; } }
|
No responses found. Be the first to respond...
|