Bubble Sorting-2
Bubble Sorting-2
int main()
cin>>n;
for(i=0; i<(n-1);Submitted
i++) to :Sir Zaid Sarfaraz (BSCS iii)
{ Submitted By :Javeria Abdul khaliq
Roll No.186
for(j=0; j<(n-i-1); j++)
if(arr[j]>arr[j+1])
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
cout<<arr[i]<<" ";
cout<<endl;
return 0;
Result
Dry Run of Above Program
because the size is 5. Therefore, n=5
And all the 5 elements gets initialized in the array arr[] in
a way that arr[0] = 5, arr[1] = 1, arr[2] = 4, arr[3] = 2,
and arr[4] = 3.
Using a for loop, initially i = 0 and checks whether it is
less than n-1 or not.
Because the condition (i<(n-1) or 0<(5-1) or 0<4)
evaluates to be true, therefore program flow goes inside
the loop
Inside the loop, there is another for loop, and j is
initially equal to 0, and the condition j<(n-i-1) or j<(5-0-
1) or j<4 evaluates to be true. Therefore, program flow
goes inside this loop.
And checks the if block's condition, that
is, arr[j]>arr[j+1] or arr[0]>arr[1] or 5>1 evaluates to
true, program flow enters the if block and executes all
three statements.
After executing all three statements, the element at
index j gets swapped with the element at index j+1.
Now arr[0]=1 and arr[1]=5, and the rest of the three
elements will be at the same index.
Now program flow goes to the updating part of the
inner for loop and increments the value of j. Now j=1
Again checks the condition, that is j<(n-i-1) or 1<(5-0-
1) or 1<4 evaluates to be true, therefore program flow
again goes inside the loop and checks the condition
of if block
If the condition evaluates to be true, then process the
three statements; otherwise, update the value of j and
checks the condition.
Continue in a similar manner with the updated value until
the outer for loop condition evaluates to false.
If the condition of the outer for loop evaluates to be
false, then program flow exits the loop.
FlowChart
Start
Arr[],n,I,j,temp
False
For j=n-1 to i
arr[]< True
arr[j-1]
temp = arr[j]
arr[j]=arr[j-1]
arr[j-1]=temp