Closed BrijeshSinghRawat closed 3 years ago
Earlier Bubble Sort Algorithm was doing unnecessary iterations even after the array was already sorted. In this Solution we will break the iteration if after one full Iteration it doesn't find any values to swap, which means Array is already Sorted.
[5, 2, 9, 1, 7, 3, 4, 505, 200] [2, 5, 1, 7, 3, 4, 9, 200, 505] [2, 1, 5, 3, 4, 7, 9, 200, 505] [1, 2, 3, 4, 5, 7, 9, 200, 505] [1, 2, 3, 4, 5, 7, 9, 200, 505] [1, 2, 3, 4, 5, 7, 9, 200, 505] [1, 2, 3, 4, 5, 7, 9, 200, 505] [1, 2, 3, 4, 5, 7, 9, 200, 505] [1, 2, 3, 4, 5, 7, 9, 200, 505]
[5, 2, 9, 1, 7, 3, 4, 505, 200] [2, 5, 1, 7, 3, 4, 9, 200, 505] [2, 1, 5, 3, 4, 7, 9, 200, 505] [1, 2, 3, 4, 5, 7, 9, 200, 505] [1, 2, 3, 4, 5, 7, 9, 200, 505]
Earlier Bubble Sort Algorithm was doing unnecessary iterations even after the array was already sorted. In this Solution we will break the iteration if after one full Iteration it doesn't find any values to swap, which means Array is already Sorted.
Number of Iterations Before Changes:
[5, 2, 9, 1, 7, 3, 4, 505, 200] [2, 5, 1, 7, 3, 4, 9, 200, 505] [2, 1, 5, 3, 4, 7, 9, 200, 505] [1, 2, 3, 4, 5, 7, 9, 200, 505] [1, 2, 3, 4, 5, 7, 9, 200, 505] [1, 2, 3, 4, 5, 7, 9, 200, 505] [1, 2, 3, 4, 5, 7, 9, 200, 505] [1, 2, 3, 4, 5, 7, 9, 200, 505] [1, 2, 3, 4, 5, 7, 9, 200, 505]
Number of Iterations After Changes:
[5, 2, 9, 1, 7, 3, 4, 505, 200] [2, 5, 1, 7, 3, 4, 9, 200, 505] [2, 1, 5, 3, 4, 7, 9, 200, 505] [1, 2, 3, 4, 5, 7, 9, 200, 505] [1, 2, 3, 4, 5, 7, 9, 200, 505]