logo

Algorithme de sélection rapide

Sélection rapide est un algorithme de sélection pour trouver le k-ème plus petit élément dans une liste non ordonnée. C'est lié au tri rapide algorithme de tri.
Exemples:

Input: arr[] = {7, 10, 4, 3, 20, 15} k = 3 Output: 7 Input: arr[] = {7, 10, 4, 3, 20, 15} k = 4 Output: 10>

L'algorithme est similaire à QuickSort. La différence est qu'au lieu de se répéter pour les deux côtés (après avoir trouvé le pivot), il se reproduit uniquement pour la partie qui contient le k-ème plus petit élément. La logique est simple, si l'indice de l'élément partitionné est supérieur à k, alors on récidive pour la partie gauche. Si l'index est le même que k, nous avons trouvé le k-ème plus petit élément et nous revenons. Si l'indice est inférieur à k, alors nous récidivons pour la partie droite. Cela réduit la complexité attendue de O(n log n) à O(n), avec le pire des cas de O(n^2).

function quickSelect(list, left, right, k) if left = right return list[left] Select a pivotIndex between left and right pivotIndex := partition(list, left, right, pivotIndex) if k = pivotIndex return list[k] else if k  C++14           // CPP program for implementation of QuickSelect  #include  using namespace std;    // Standard partition process of QuickSort().  // It considers the last element as pivot  // and moves all smaller element to left of  // it and greater elements to right  int partition(int arr[], int l, int r)  {   int x = arr[r], i = l;   for (int j = l; j <= r - 1; j++) {   if (arr[j] <= x) {   swap(arr[i], arr[j]);   i++;   }   }   swap(arr[i], arr[r]);   return i;  }    // This function returns k'th smallest  // element in arr[l..r] using QuickSort  // based method. ASSUMPTION: ALL ELEMENTS  // IN ARR[] ARE DISTINCT  int kthSmallest(int arr[], int l, int r, int k)  {   // If k is smaller than number of   // elements in array   if (k>0 &&k<= r - l + 1) {     // Partition the array around last   // element and get position of pivot   // element in sorted array   int index = partition(arr, l, r);     // If position is same as k   if (index - l == k - 1)   return arr[index];     // If position is more, recur   // for left subarray   if (index - l>k - 1) return kthSmallest(arr, l, index - 1, k);     // Sinon, récurrent pour le sous-tableau droit, return kthSmallest(arr, index + 1, r, k - index + l - 1);   } // Si k est supérieur au nombre // d'éléments du tableau, return INT_MAX ;  } // Programme pilote pour tester les méthodes ci-dessus int main() { int arr[] = { 10, 4, 5, 8, 6, 11, 26 };   int n = taillede(arr) / taillede(arr[0]);   entier k = 3 ;   cout<< 'K-th smallest element is '  << kthSmallest(arr, 0, n - 1, k);   return 0;  }   Java           // Java program of Quick Select  import java.util.Arrays;    class GFG {     // partition function similar to quick sort   // Considers last element as pivot and adds   // elements with less value to the left and   // high value to the right and also changes   // the pivot position to its respective position   // in the final array.   public static int partition(int[] arr, int low,   int high)   {   int pivot = arr[high], pivotloc = low;   for (int i = low; i <= high; i++) {   // inserting elements of less value   // to the left of the pivot location   if (arr[i]   int temp = arr[i];   arr[i] = arr[pivotloc];   arr[pivotloc] = temp;   pivotloc++;   }   }     // swapping pivot to the final pivot location   int temp = arr[high];   arr[high] = arr[pivotloc];   arr[pivotloc] = temp;     return pivotloc;   }     // finds the kth position (of the sorted array)   // in a given unsorted array i.e this function   // can be used to find both kth largest and   // kth smallest element in the array.   // ASSUMPTION: all elements in arr[] are distinct   public static int kthSmallest(int[] arr, int low,   int high, int k)   {   // find the partition   int partition = partition(arr, low, high);     // if partition value is equal to the kth position,   // return value at k.   if (partition == k - 1)   return arr[partition];     // if partition value is less than kth position,   // search right side of the array.   else if (partition 1)   return kthSmallest(arr, partition + 1, high, k);     // if partition value is more than kth position,   // search left side of the array.   else  return kthSmallest(arr, low, partition - 1, k);   }     // Driver Code   public static void main(String[] args)   {   int[] array = new int[] { 10, 4, 5, 8, 6, 11, 26 };   int[] arraycopy   = new int[] { 10, 4, 5, 8, 6, 11, 26 };     int kPosition = 3;   int length = array.length;     if (kPosition>longueur) { System.out.println('Index hors limite');   } else { // trouver la kième plus petite valeur System.out.println( 'K-ième plus petit élément du tableau : ' + kthSmallest(arraycopy, 0, length - 1, kPosition));   } } } // Ce code est fourni par Saiteja Pamulapati Python3 # Programme Python3 de Quick Select # Processus de partitionnement standard de QuickSort().  # Il considère le dernier élément comme pivot # et déplace tous les éléments plus petits à gauche de # celui-ci et les éléments plus grands vers la droite def partition(arr, l, r): x = arr[r] i = l for j in range(l, r) : si arr[j]<= x:   arr[i], arr[j] = arr[j], arr[i]   i += 1    arr[i], arr[r] = arr[r], arr[i]   return i    # finds the kth position (of the sorted array)  # in a given unsorted array i.e this function  # can be used to find both kth largest and  # kth smallest element in the array.  # ASSUMPTION: all elements in arr[] are distinct  def kthSmallest(arr, l, r, k):     # if k is smaller than number of   # elements in array   if (k>0 et k<= r - l + 1):     # Partition the array around last   # element and get position of pivot   # element in sorted array   index = partition(arr, l, r)     # if position is same as k   if (index - l == k - 1):   return arr[index]     # If position is more, recur   # for left subarray   if (index - l>k - 1) : return kthSmallest(arr, l, index - 1, k) # Sinon, récurrent pour le sous-tableau droit, return kthSmallest(arr, index + 1, r, k - index + l - 1) print('Index out of lié') # Code du pilote arr = [ 10, 4, 5, 8, 6, 11, 26 ] n = len(arr) k = 3 print('K-ème plus petit élément est ', end = ' ') print(kthSmallest(arr, 0, n - 1, k)) # Ce code est fourni par Muskan Kalra.   C# // Programme C# de Quick Select utilisant System ;    class GFG { // fonction de partition similaire au tri rapide // Considère le dernier élément comme pivot et ajoute // les éléments avec moins de valeur à gauche et // une valeur élevée à droite et change également // la position du pivot à sa position respective / / dans le tableau en lecture seule.   partitions int statiques (int []arr, int bas, int haut) { int pivot = arr [haut], pivotloc = bas, temp;   pour (int je = faible; je<= high; i++)   {   // inserting elements of less value   // to the left of the pivot location   if(arr[i]   {   temp = arr[i];   arr[i] = arr[pivotloc];   arr[pivotloc] = temp;   pivotloc++;   }   }     // swapping pivot to the readonly pivot location   temp = arr[high];   arr[high] = arr[pivotloc];   arr[pivotloc] = temp;     return pivotloc;   }     // finds the kth position (of the sorted array)   // in a given unsorted array i.e this function   // can be used to find both kth largest and   // kth smallest element in the array.   // ASSUMPTION: all elements in []arr are distinct   static int kthSmallest(int[] arr, int low,   int high, int k)   {   // find the partition   int partition = partitions(arr,low,high);     // if partition value is equal to the kth position,   // return value at k.   if(partition == k)   return arr[partition];     // if partition value is less than kth position,   // search right side of the array.   else if(partition   return kthSmallest(arr, partition + 1, high, k );     // if partition value is more than kth position,   // search left side of the array.   else  return kthSmallest(arr, low, partition - 1, k );   }     // Driver Code   public static void Main(String[] args)   {   int[] array = {10, 4, 5, 8, 6, 11, 26};   int[] arraycopy = {10, 4, 5, 8, 6, 11, 26};     int kPosition = 3;   int length = array.Length;     if(kPosition>longueur) { Console.WriteLine('Index hors limite');   } else { // recherche la kième plus petite valeur Console.WriteLine('K-ième plus petit élément du tableau : ' + kthSmallest(arraycopy, 0, length - 1, kPosition - 1));   } } } // Ce code est fourni par 29AjayKumar Javascript // Programme Javascript de Quick Select // fonction de partition similaire au tri rapide // Considére le dernier élément comme pivot et ajoute // des éléments avec moins de valeur à gauche et // une valeur élevée vers la droite et modifie également // la position du pivot vers sa position respective // ​​dans le tableau final.  function _partition(arr, low, high) { let pivot = arr[high], pivotloc = low;   pour (soit i = faible ; i<= high; i++)   {     // inserting elements of less value   // to the left of the pivot location   if (arr[i]   {   let temp = arr[i];   arr[i] = arr[pivotloc];   arr[pivotloc] = temp;   pivotloc++;   }   }     // swapping pivot to the final pivot location   let temp = arr[high];   arr[high] = arr[pivotloc];   arr[pivotloc] = temp;     return pivotloc;  }    // finds the kth position (of the sorted array)   // in a given unsorted array i.e this function   // can be used to find both kth largest and   // kth smallest element in the array.   // ASSUMPTION: all elements in arr[] are distinct  function kthSmallest(arr, low, high, k)  {     // find the partition   let partition = _partition(arr, low, high);     // if partition value is equal to the kth position,   // return value at k.   if (partition == k - 1)   return arr[partition];     // if partition value is less than kth position,   // search right side of the array.   else if (partition   return kthSmallest(arr, partition + 1, high, k);     // if partition value is more than kth position,   // search left side of the array.   else  return kthSmallest(arr, low, partition - 1, k);  }    // Driver Code  let array = [ 10, 4, 5, 8, 6, 11, 26];  let arraycopy = [10, 4, 5, 8, 6, 11, 26 ];  let kPosition = 3;  let length = array.length;    if (kPosition>longueur) { document.write('Index hors limite ');  } else { // trouver la kième plus petite valeur document.write( 'K-ème plus petit élément du tableau : ' + kthSmallest(arraycopy, 0, length - 1, kPosition)+' ');  } // Ce code est fourni par rag2127 Résultat : Le K-ème plus petit élément est 6 Points importants : Comme le tri rapide, il est rapide en pratique, mais a de mauvaises performances dans le pire des cas. Il est utilisé dans Le processus de partitionnement est le même que QuickSort, seul le code récursif diffère. Il existe un algorithme qui trouve le k-ème plus petit élément de O(n) dans le pire des cas, mais QuickSelect fonctionne mieux en moyenne.    Fonction C++ associée : std::nth_element en C++>