简体   繁体   中英

average number of swaps in dutch national flag

I just want to know how can I get the average number of swaps in the two colors dutch national flag. sorting positive and negative numbers instead of colors. I'm assuming that the negative numbers are equal to the positive numbers and the array's numbers are given a random configuration, I'm not sure if my assumption is correct.

Algorithm(A[0…n-1]):
    i ← 0
    j ← n - 1
    while i ≤ j:
        if A[i] < 0:            
           i ← i + 1
        else:
           swap(A[i], A[j])
           j ← j - 1

Thank you.

If the distribution of the positives and negatives is uniform, the first element is positive with probability 1/2 . After the first iteration, the array is shortened by one element and the distribution of the subarray is still uniform (moving an element is a neutral operation).

There are exactly n iterations before the subarray is empty thus the average number of swaps is n/2 . More precisely, the number of swaps follows a Binomial law with parameters 1/2 , n (this is a Bernouilli scheme).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM