@ayush693 hn its like bubble sort , dekho hm upar wala loop to n-1 times chla rhe hai woh number of passes ke lie hai ,aur andr wala loop hmare elements ko compare krne ke lie ye n-i-1 islie chl rha hai kyuunki har pass me apna akhri element sahi position pr ajayega suppose for i=0 andr wala loop n-1 ytak chlega ye compare krne ke bad ab i=1 hoga fir ye n-1-1 that is n-2 tk chlega kyunki akhri element sahi position pr achuka hai islie usse ek kam tk chalyaenge andr wala loop,see eg:
this ex is on number array but same logic is for string array bs comapreto hmne apna bnaya hai:
Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, 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, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )