Bubble Sort
Bubble Sort
Bubble Sort
Sorting
Bubble Sort
"1
ABHISHEK SHUKLA
Bubble Sort : Exchange two adjacent elements if they are out of order.
Repeat until array is sorted.
Insertion sort : Scan successive elements for an out-of-order item, then insert
the item in the proper place.
Selection sort : Find the smallest element in the array, and put it in the
proper place. Swap it with the value in the first position. Repeat until array is
sorted.
Quick sort : Partition the array into two segments. In the first segment, all
elements are less than or equal to the pivot value. In the second segment, all
elements are greater than or equal to the pivot value. Finally, sort the two
segments recursively.
Merge sort : Divide the list of elements in two parts, sort the two parts
individually and then merge it.
Bubble sort
Let us consider that we have a list of integers in a form of an array A with index
0 to 5.
"2
ABHISHEK SHUKLA
"3
ABHISHEK SHUKLA
T(n) = (n-1)*(n-1)*C
= Cn2 - 2Cn + 1
Hence the time complexity will be highest power of n i.e. O(n) .Since this is
O(n) runtime, and hence is very slow for large data sets.
We can do couple of things to improve time complexity . The first thing we can
do is we need not to run the second loop always till array.length-2 times
because at any stage the array will have some part sorted some not. There is no
point to run the loop for sorted path because there will be not swapping in that
part.For the first pass we can run the inner loop till array.length-2 and
for the second pass we can run the inner loop till array.length-3 and we
will be good. and hence we can run the inner loop till array.length-i-1
Hence our new code will be:
ABHISHEK SHUKLA
And in this way we will avoid the redundant passes when the array is already
sorted. By this modification if we input an already sorted array the inner loop
will execute only once.
The single best advantage of a bubble sort is that it is very simple to
understand and it is a stable sort that requires no additional memory, since all
swaps are made in place.
"5