logo

QuickSort – Štruktúra údajov a návody na algoritmy

QuickSort je triediaci algoritmus založený na Algoritmus rozdeľuj a panuj ktorý vyberie prvok ako pivot a rozdelí dané pole okolo vybraného pivotu umiestnením pivotu do správnej polohy v zoradenom poli.

Ako funguje QuickSort?

Kľúčový proces v quickSort je a oddiel() . Cieľom oddielov je umiestniť otočný čap (akýkoľvek prvok môže byť zvolený ako čap) na správnu pozíciu v zoradenom poli a umiestniť všetky menšie prvky naľavo od otočného bodu a všetky väčšie prvky napravo od otočného bodu. .

Rozdelenie sa vykonáva rekurzívne na každej strane čapu po umiestnení čapu do správnej polohy a tým sa pole nakoniec zoradí.



Ako funguje Quicksort

Ako funguje Quicksort

gimp odstraňuje pozadie
Odporúčaný postup Rýchle zoradenie Vyskúšajte to!

Voľba pivotu:

Existuje veľa rôznych možností výberu pivot.

  • Vždy vyberte prvý prvok ako pivot .
  • Vždy vyberte posledný prvok ako pivot (implementované nižšie)
  • Vyberte náhodný prvok ako pivot .
  • Vyberte stred ako pivot.

Algoritmus rozdelenia:

Logika je jednoduchá, začíname od prvku úplne vľavo a sledujeme index menších (alebo rovnakých) prvkov ako i . Ak pri prechádzaní nájdeme menší prvok, vymeníme aktuálny prvok za arr[i]. V opačnom prípade ignorujeme aktuálny prvok.

Poďme pochopiť fungovanie oddielu a algoritmu rýchleho triedenia pomocou nasledujúceho príkladu:

Zvážte: arr[] = {10, 80, 30, 90, 40}.

  • Porovnajte 10 s čapom a keďže je menší ako čap, usporiadajte ho podľa toho.

Partícia v QuickSort: Porovnajte pivot s 10

  • Porovnajte 80 s pivotom. Je väčší ako pivot.

Partícia v QuickSort: Porovnajte pivot s 80

localdatetime java
  • Porovnajte 30 s pivotom. Je menší ako pivot, preto ho podľa toho usporiadajte.

Partícia v QuickSort: Porovnajte pivot s 30

  • Porovnajte 90 s pivotom. Je väčší ako pivot.

Partícia v QuickSort: Porovnajte pivot s 90

  • Umiestnite čap do správnej polohy.

Partícia v QuickSort: Umiestnite otočný čap do správnej polohy

Ilustrácia Quicksort:

Keďže proces rozdeľovania prebieha rekurzívne, neustále umiestňuje pivot do svojej skutočnej polohy v zoradenom poli. Opakovaným umiestnením pivotov do ich skutočnej polohy sa pole zoradí.

Postupujte podľa obrázkov nižšie, aby ste pochopili, ako rekurzívna implementácia algoritmu oddielu pomáha triediť pole.

top 10 hentai
  • Počiatočný oddiel na hlavnom poli:

Quicksort: Vykonanie rozdelenia

  • Rozdelenie podpolí:

Quicksort: Vykonanie rozdelenia

Implementácia kódu rýchleho triedenia:

C++
#include  using namespace std; int partition(int arr[],int low,int high) {  //choose the pivot    int pivot=arr[high];  //Index of smaller element and Indicate  //the right position of pivot found so far  int i=(low-1);    for(int j=low;j<=high-1;j++)  {  //If current element is smaller than the pivot  if(arr[j]
C
// C program for QuickSort #include  // Utility function to swap tp integers void swap(int* p1, int* p2) {  int temp;  temp = *p1;  *p1 = *p2;  *p2 = temp; } int partition(int arr[], int low, int high) {  // choose the pivot  int pivot = arr[high];  // Index of smaller element and Indicate  // the right position of pivot found so far  int i = (low - 1);  for (int j = low; j <= high - 1; j++) {  // If current element is smaller than the pivot  if (arr[j] < pivot) {  // Increment index of smaller element  i++;  swap(&arr[i], &arr[j]);  }  }  swap(&arr[i + 1], &arr[high]);  return (i + 1); } // The Quicksort function Implement void quickSort(int arr[], int low, int high) {  // when low is less than high  if (low < high) {  // pi is the partition return index of pivot  int pi = partition(arr, low, high);  // Recursion Call  // smaller element than pivot goes left and  // higher element goes right  quickSort(arr, low, pi - 1);  quickSort(arr, pi + 1, high);  } } int main() {  int arr[] = { 10, 7, 8, 9, 1, 5 };  int n = sizeof(arr) / sizeof(arr[0]);    // Function call  quickSort(arr, 0, n - 1);    // Print the sorted array  printf('Sorted Array
');  for (int i = 0; i < n; i++) {  printf('%d ', arr[i]);  }  return 0; } // This Code is Contributed By Diwakar Jha>
Java
// Java implementation of QuickSort import java.io.*; class GFG {  // A utility function to swap two elements  static void swap(int[] arr, int i, int j)  {  int temp = arr[i];  arr[i] = arr[j];  arr[j] = temp;  }  // This function takes last element as pivot,  // places the pivot element at its correct position  // in sorted array, and places all smaller to left  // of pivot and all greater elements to right of pivot  static int partition(int[] arr, int low, int high)  {  // Choosing the pivot  int pivot = arr[high];  // Index of smaller element and indicates  // the right position of pivot found so far  int i = (low - 1);  for (int j = low; j <= high - 1; j++) {  // If current element is smaller than the pivot  if (arr[j] < pivot) {  // Increment index of smaller element  i++;  swap(arr, i, j);  }  }  swap(arr, i + 1, high);  return (i + 1);  }  // The main function that implements QuickSort  // arr[] -->Pole, ktoré sa má zoradiť, // low --> Počiatočný index, // high --> Ending index static void quickSort(int[] arr, int low, int high) { if (low< high) {  // pi is partitioning index, arr[p]  // is now at right place  int pi = partition(arr, low, high);  // Separately sort elements before  // partition and after partition  quickSort(arr, low, pi - 1);  quickSort(arr, pi + 1, high);  }  }  // To print sorted array  public static void printArr(int[] arr)  {  for (int i = 0; i < arr.length; i++) {  System.out.print(arr[i] + ' ');  }  }  // Driver Code  public static void main(String[] args)  {  int[] arr = { 10, 7, 8, 9, 1, 5 };  int N = arr.length;  // Function call  quickSort(arr, 0, N - 1);  System.out.println('Sorted array:');  printArr(arr);  } } // This code is contributed by Ayush Choudhary // Improved by Ajay Virmoti>
Python
# Python3 implementation of QuickSort # Function to find the partition position def partition(array, low, high): # Choose the rightmost element as pivot pivot = array[high] # Pointer for greater element i = low - 1 # Traverse through all elements # compare each element with pivot for j in range(low, high): if array[j] <= pivot: # If element smaller than pivot is found # swap it with the greater element pointed by i i = i + 1 # Swapping element at i with element at j (array[i], array[j]) = (array[j], array[i]) # Swap the pivot element with # the greater element specified by i (array[i + 1], array[high]) = (array[high], array[i + 1]) # Return the position from where partition is done return i + 1 # Function to perform quicksort def quicksort(array, low, high): if low < high: # Find pivot element such that # element smaller than pivot are on the left # element greater than pivot are on the right pi = partition(array, low, high) # Recursive call on the left of pivot quicksort(array, low, pi - 1) # Recursive call on the right of pivot quicksort(array, pi + 1, high) # Driver code if __name__ == '__main__': array = [10, 7, 8, 9, 1, 5] N = len(array) # Function call quicksort(array, 0, N - 1) print('Sorted array:') for x in array: print(x, end=' ') # This code is contributed by Adnan Aliakbar>
C#
// C# implementation of QuickSort using System; class GFG {  // A utility function to swap two elements  static void swap(int[] arr, int i, int j)  {  int temp = arr[i];  arr[i] = arr[j];  arr[j] = temp;  }  // This function takes last element as pivot,  // places the pivot element at its correct position  // in sorted array, and places all smaller to left  // of pivot and all greater elements to right of pivot  static int partition(int[] arr, int low, int high)  {  // Choosing the pivot  int pivot = arr[high];  // Index of smaller element and indicates  // the right position of pivot found so far  int i = (low - 1);  for (int j = low; j <= high - 1; j++) {  // If current element is smaller than the pivot  if (arr[j] < pivot) {  // Increment index of smaller element  i++;  swap(arr, i, j);  }  }  swap(arr, i + 1, high);  return (i + 1);  }  // The main function that implements QuickSort  // arr[] -->Pole, ktoré sa má zoradiť, // low --> Počiatočný index, // high --> Ending index static void quickSort(int[] arr, int low, int high) { if (low< high) {  // pi is partitioning index, arr[p]  // is now at right place  int pi = partition(arr, low, high);  // Separately sort elements before  // and after partition index  quickSort(arr, low, pi - 1);  quickSort(arr, pi + 1, high);  }  }  // Driver Code  public static void Main()  {  int[] arr = { 10, 7, 8, 9, 1, 5 };  int N = arr.Length;  // Function call  quickSort(arr, 0, N - 1);  Console.WriteLine('Sorted array:');  for (int i = 0; i < N; i++)  Console.Write(arr[i] + ' ');  } } // This code is contributed by gfgking>
JavaScript
// Function to partition the array and return the partition index function partition(arr, low, high) {  // Choosing the pivot  let pivot = arr[high];    // Index of smaller element and indicates the right position of pivot found so far  let i = low - 1;    for (let j = low; j <= high - 1; j++) {  // If current element is smaller than the pivot  if (arr[j] < pivot) {  // Increment index of smaller element  i++;  [arr[i], arr[j]] = [arr[j], arr[i]]; // Swap elements  }  }    [arr[i + 1], arr[high]] = [arr[high], arr[i + 1]]; // Swap pivot to its correct position  return i + 1; // Return the partition index } // The main function that implements QuickSort function quickSort(arr, low, high) {  if (low < high) {  // pi is the partitioning index, arr[pi] is now at the right place  let pi = partition(arr, low, high);    // Separately sort elements before partition and after partition  quickSort(arr, low, pi - 1);  quickSort(arr, pi + 1, high);  } } // Driver code let arr = [10, 7, 8, 9, 1, 5]; let N = arr.length; // Function call quickSort(arr, 0, N - 1); console.log('Sorted array:'); console.log(arr.join(' '));>
PHP
 // code ?>// Táto funkcia sa uskutoční ako posledný prvok ako pivot // Umiestnite pivot do správnej polohy // V triedenom poli a umiestni všetky menšie vľavo // od otočného bodu a všetky väčšie prvky napravo od oddielu funkcie pivot (&$arr, $low,$high) { // Vyberte kontingenčný prvok $pivot= $arr[$high]; // Index menšieho prvku a označuje // Správnu pozíciu pivotu $i=($low-1); for($j=$nízka;$j<=$high-1;$j++) { if($arr[$j]<$pivot) { // Increment index of smaller element $i++; list($arr[$i],$arr[$j])=array($arr[$j],$arr[$i]); } } // Pivot element as correct position list($arr[$i+1],$arr[$high])=array($arr[$high],$arr[$i+1]); return ($i+1); } // The main function that implement as QuickSort // arr[]:- Array to be sorted // low:- Starting Index //high:- Ending Index function quickSort(&$arr,$low,$high) { if($low<$high) { // pi is partition $pi= partition($arr,$low,$high); // Sort the array // Before the partition of Element quickSort($arr,$low,$pi-1); // After the partition Element quickSort($arr,$pi+1,$high); } } // Driver Code $arr= array(10,7,8,9,1,5); $N=count($arr); // Function Call quickSort($arr,0,$N-1); echo 'Sorted Array:
'; for($i=0;$i<$N;$i++) { echo $arr[$i]. ' '; } //This code is contributed by Diwakar Jha>

Výkon
Sorted Array 1 5 7 8 9 10>

Analýza zložitosti rýchleho triedenia :

Časová zložitosť:

  • Najlepší prípad : Ω (N log (N))
    Najlepší scenár pre rýchle triedenie nastane, keď pivot zvolený v každom kroku rozdelí pole na približne rovnaké polovice.
    V tomto prípade algoritmus vytvorí vyvážené oddiely, čo povedie k efektívnemu triedeniu.
  • Priemerný prípad: θ (N log (N))
    Priemerný výkon Quicksortu je v praxi zvyčajne veľmi dobrý, čo z neho robí jeden z najrýchlejších triediacich algoritmov.
  • Najhorší prípad: O(N2)
    Najhorší scenár pre Quicksort nastane, keď pivot v každom kroku konzistentne vedie k vysoko nevyváženým oddielom. Keď je pole už zoradené a pivot je vždy vybraný ako najmenší alebo najväčší prvok. Na zmiernenie najhoršieho scenára sa používajú rôzne techniky, ako je výber dobrého pivotu (napr. medián troch) a použitie náhodného algoritmu (Randomized Quicksort ) na premiešanie prvku pred zoradením.
  • Pomocný priestor: O(1), ak neberieme do úvahy rekurzívny zásobníkový priestor. Ak vezmeme do úvahy rekurzívny zásobníkový priestor, v najhoršom prípade by to mohlo urobiť rýchle triedenie O ( N ).

Výhody rýchleho triedenia:

  • Je to algoritmus rozdeľuj a panuj, ktorý uľahčuje riešenie problémov.
  • Je efektívny pri veľkých súboroch údajov.
  • Má nízku réžiu, pretože na fungovanie vyžaduje len malé množstvo pamäte.

Nevýhody rýchleho triedenia:

  • Má časovú zložitosť v najhoršom prípade O(N2), ku ktorému dochádza, keď je pivot zvolený zle.
  • Nie je to dobrá voľba pre malé súbory údajov.
  • Nejde o stabilné zoradenie, čo znamená, že ak majú dva prvky rovnaký kľúč, v zoradenom výstupe sa v prípade rýchleho zoradenia nezachová ich relatívne poradie, pretože tu zamieňame prvky podľa polohy pivotu (bez zohľadnenia ich pôvodného pozície).