We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
defbubble(array):total_swaps=0foriinrange(len(array)):# track swaps in single array traversalnumber_of_swaps=0forjinrange(len(array)-1):# swap adjacent elements if they're in the wrong orderifarray[j]>array[j+1]:temp=array[j]array[j]=array[j+1]array[j+1]=tempnumber_of_swaps+=1# if no swaps, array is sortedifnumber_of_swaps==0:breaktotal_swaps+=number_of_swapsreturntotal_swaps,array[0],array[-1]if__name__=='__main__':n=int(input().strip())a=list(map(int,input().rstrip().split()))swaps,first,last=bubble(a)print(f'Arrayissortedin{swaps}swaps.')print(f'FirstElement:{first}')print(f'LastElement:{last}')
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Day 20: Sorting
You are viewing a single comment's thread. Return to all comments →