Just want to rearrange the data in array so that similar items are not next to each. The data should not be removed from the array, if it can't be rearranged it can be put at the end of the array. But keeping the original order is necessary.
Example
1 1 2 => 1 2 1
1 1 1 2 3 => 1 2 1 3 1
1 1 2 1 3 3 5 1 => 1 2 1 3 1 3 5 1
1 1 1 1 1 1 2 => 1 2 1 1 1 1 1
8 2 1 3 7 2 5 => rearrange not needed
8 2 2 2 7 2 5 2 => 8 2 7 2 5 2 2 // keep the original order
EDIT: Added example to show keeping original order is needed
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.
A simple solution would be to use efficient sorting algorithms like Merge Sort, Quicksort, Heapsort, etc., that can solve this problem in O(n. log(n)) time, but those will not take advantage of the fact that there are many duplicated values in the array. A better approach is to use a counting sort.
If you use the native array sort function, you can pass in a custom comparator to be used when sorting the array. The comparator should return a negative number if the first value is less than the second, zero if they're equal, and a positive number if the first value is greater.
Swap elements at small even indexes with their higher antipodal counterparts:
for ( i=0; i < arr.length/2; i+=2 )
arr.swap(i,arr.length-1-i);
Edit: Okay, we should redefine the antipodal counterparts. Maybe this one is better: mixing the first and third quartile (denoted x, y in illustration), and mixing the second and third quartile (denoted u, v, w). Let the counterparts ascend parallel.
25% 50% 75%
| | |
-----[----[----[----
11122334455667788999
x y u v w x y u v w <-- u, v, w, x, y indicate swap positions
16172839495161738495
Hmm. Bubblesort comes to mind, but with a three-element comparison; that is, if item[x]
and item[x + 1]
are the same and item[x + 2]
is different, swap item[x + 1]
and item[x + 2]
. Repeat iterating through the list until no swaps occur. Execution order is, of course, horrible, but that should meet your needs.
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