anku580 / Java-Algorithms

This repository contains java algorithms and some interview questions.
11 stars 57 forks source link

Improving the Performance of Bubble Sort Algorithm. #74

Closed BrijeshSinghRawat closed 3 years ago

BrijeshSinghRawat commented 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.

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]