Maison  >  Article  >  développement back-end  >  Tri rapide à 3 voies (problème du drapeau néerlandais)

Tri rapide à 3 voies (problème du drapeau néerlandais)

王林
王林avant
2023-09-16 19:53:021032parcourir

Tri rapide à 3 voies (problème du drapeau néerlandais)

Ici, nous verrons la technique de tri rapide, mais nous utiliserons le tri rapide à trois voies. La technique de tri rapide de base trouve simplement un élément comme pivot, puis divise le tableau autour du pivot, et après cela, récidive sur les sous-tableaux gauche et droit du pivot.

Le tri rapide à trois voies est similaire, mais comporte trois parties. Le tableau arr[1 à n] est divisé en trois parties.

  • arr[1 à i]
  • arr[i + 1, j]
  • arr[j + 1, n]

algorithme

partition(arr, gauche, droite, i, j) −

begin
   if right &ndash; left <= 1, then
      if arr[right] < arr[left], then
         swap arr[right] and arr[left]
      i := left
      j := right
      return
   end if
   mid := left, pivot = arr[right]
   while mid <= right, do
      if arr[mid] < pivot, then
         swap arr[left], arr[mid]
         increase left and mid by 1
      else if arr[mid] = pivot, then increase mid by 1
      else
         swap arr[mid], arr[right]
         decrease right by 1
   done
   i := left &ndash; 1
   j := mid
end

Tri rapide (arr, gauche, droite) - La traduction chinoise de

begin
   if left >= right, then
      return
   end if
   define i and j
   partition(arr, left, right, i, j)
   quicksort(arr, left, i)
   quicksort(arr, j, right)
end

Example

est :

Example

#include<iostream>
#include<vector>
using namespace std;
void partition(int arr[], int left, int right, int &i, int &j) {
   if (right - left <= 1) {
      if (arr[right] < arr[left])
         swap(arr[right], arr[left]);
      i = left;
      j = right;
      return;
}
int mid = left;
int pivot = arr[right];
while (mid <= right) {
   if (arr[mid]<pivot)
      swap(arr[left++], arr[mid++]);
      else if (arr[mid]==pivot)
         mid++;
      else if (arr[mid] > pivot)
         swap(arr[mid], arr[right--]);
   }
   i = left-1;
   j = mid;
}
void quicksort(int arr[], int left, int right) {
   if (left >= right) //1 or 0 elements
      return;
   int i, j;
   partition(arr, left, right, i, j);
   quicksort(arr, left, i);
   quicksort(arr, j, right);
}
void display(int arr[], int n) {
   for (int i = 0; i < n; ++i)
   cout << " " << arr[i];
   cout << endl;
}
int main() {
   int a[] = {4, 9, 4, 3, 1, 9, 4, 3, 9, 4, 3, 1, 4};
   int n = sizeof(a) / sizeof(int);
   display(a, n);
   quicksort(a, 0, n - 1);
   display(a, n);
}

Output

4 9 4 3 1 9 4 3 9 4 3 1 4
1 1 3 3 3 4 4 4 4 4 9 9 9

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer