Saltar al contenido

ejemplo de código de algoritmo de bandera nacional holandesa

Ejemplo 1: problema de la bandera nacional holandesa

Initially all array values are treated as unpartitioned:
[unpartitioned values]
Array split into four parts as the iteration proceeds:
[ values < mid | values = mid | unpartitioned values | values > mid ]

procedure three-way-partition(A : array of values, mid : value):
    i ← 0
    j ← 0
    k ← size of A - 1

    while j <= k:
        if A[j] < mid:
            swap A[i] and A[j]
            i ← i + 1
            j ← j + 1
        else if A[j] > mid:
            swap A[j] and A[k]
            k ← k - 1
        else:          
            j ← j + 1

Ejemplo 2: ordenar una matriz de 0s 1s y 2s

Approach: Count the number of 0s, 1s and 2s in the given array. 
Then store all the 0s in the beginning followed by all the 1s then
all the 2s.
Algorithm:
1)Keep three counter c0 to count 0s, c1 to count 1s and c2 to count 2s
2)Traverse through the array and increase the count of c0 is the 
  element is 0,increase the count of c1 if the element is 1 and 
  increase the count of c2 if the element is 2
3)Now again traverse the array and replace first c0 elements with 0, 
  next c1 elements with 1 and next c2 elements with 2.

//GfG PseudoCode
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *