For example, if the numbers are:
30, 12, 49, 6, 10, 50, 13
The array will be:
[10, 6, 30, 12, 49, 13, 50]
As you can see:
The numbers are all different and real. I need the most efficient algorithm.
The sort() method allows you to sort elements of an array in place. Besides returning the sorted array, the sort() method changes the positions of the elements in the original array. By default, the sort() method sorts the array elements in ascending order with the smallest value first and largest value last.
Approach(Naive Approach): Navigate the numbers from 0 to n-1. Now navigate through array. If (i==a[j]) , then replace the element at i position with a[j] position. If there is any element in which -1 is used instead of the number then it will be replaced automatically.
The idea is to start from the second array element and increment the index by 2 for each loop's iteration. If the last element is greater than the current element, swap the elements. Similarly, if the next element is greater than the current element, swap both elements.
The simplest trick is sort the array first and count the number of elements in the array. So for example if you have 10 elements then your first element is less than 9 and likewise the second element is smaller than 8 and so on.
This can be done in O(n):
Of course, this assumes that all elements are distinct, otherwise sometimes it will fail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With