In your above algorithm, if the length
of your array is 5
, it will execute the inner if statement
25
times. In general when you will have a list of n
size, it will for sure do n^2
operations excluding the for loop
and swapping
.
For a list of size 10^6
, it will be 10^12
operations atleast. C
or C++
do around 10^9
operations per second. So this code of yours will take 10^3
seconds which is more than half an hour. So that’s very much inefficient.
There are better sorting algorithms which you can use instead of bubble sort
as they are faster than this.
A lot of other techniques are also there but these are most common used.
Apart from that, you don’t need to implement these algorithms as one of the most efficient one is already implemented in standard library of mostly each language from C
to Rust
. You can just use that implementation and even pass you own comparator
function if you want.
solved Sorting algorithms more efficient than bubble sort [closed]