logo

Algoritme d'ordenació ràpida

En aquest article, parlarem de l'algoritme Quicksort. El procediment de treball de Quicksort també és senzill. Aquest article serà molt útil i interessant per als estudiants, ja que podrien enfrontar-se a una pregunta ràpida en els seus exàmens. Per tant, és important parlar del tema.

L'ordenació és una manera d'ordenar els elements d'una manera sistemàtica. Quicksort és l'algorisme d'ordenació àmpliament utilitzat que fa n registre n comparacions en cas mitjà per ordenar una matriu de n elements. És un algorisme d'ordenació més ràpid i molt eficient. Aquest algorisme segueix l'enfocament de dividir i conquerir. Dividir i vencer és una tècnica per descompondre els algorismes en subproblemes, després resoldre'ls i tornar a combinar els resultats per resoldre el problema original.

zeenat aman actor

Dividir: A Dividir, primer seleccioneu un element pivot. Després d'això, particioneu o reorganitzeu la matriu en dues submatrius de manera que cada element de la submatriu esquerra sigui menor o igual que l'element pivot i cada element de la submatriu dreta sigui més gran que l'element pivot.

Conquerir: De manera recursiva, ordena dos subbarrays amb Quicksort.

Combina: Combina la matriu ja ordenada.

Quicksort tria un element com a pivot i, a continuació, particiona la matriu donada al voltant de l'element pivot triat. En l'ordenació ràpida, una matriu gran es divideix en dues matrius en les quals una conté valors que són més petits que el valor especificat (Pivot) i una altra matriu conté els valors que són més grans que el pivot.

Després d'això, les submatrius esquerra i dreta també es divideixen utilitzant el mateix enfocament. Continuarà fins que l'element únic romangui a la submatriu.

Algoritme d'ordenació ràpida

L'elecció del pivot

Escollir un bon pivot és necessari per a la ràpida implementació de quicksort. Tanmateix, és típic determinar un bon pivot. Algunes de les maneres de triar un pivot són les següents:

  • El pivot pot ser aleatori, és a dir, seleccioneu el pivot aleatori de la matriu donada.
  • El pivot pot ser l'element més a la dreta de l'element més a l'esquerra de la matriu donada.
  • Seleccioneu la mitjana com a element de pivot.

Algorisme

Algorisme:

 QUICKSORT (array A, start, end) { 1 if (start <end) 2 3 4 5 6 { p="partition(A," start, end) quicksort (a, - 1) + 1, } < pre> <p> <strong>Partition Algorithm:</strong> </p> <p>The partition algorithm rearranges the sub-arrays in a place.</p> <pre> PARTITION (array A, start, end) { 1 pivot ? A[end] 2 i ? start-1 3 for j ? start to end -1 { 4 do if (A[j] <pivot) 1 5 6 7 8 9 { then i ? + swap a[i] with a[j] }} a[i+1] a[end] return i+1 } < pre> <h2>Working of Quick Sort Algorithm</h2> <p>Now, let&apos;s see the working of the Quicksort Algorithm.</p> <p>To understand the working of quick sort, let&apos;s take an unsorted array. It will make the concept more clear and understandable.</p> <p>Let the elements of array are -</p> <img src="//techcodeview.com/img/ds-tutorial/75/quick-sort-algorithm-2.webp" alt="Quick Sort Algorithm"> <p>In the given array, we consider the leftmost element as pivot. So, in this case, a[left] = 24, a[right] = 27 and a[pivot] = 24.</p> <p>Since, pivot is at left, so algorithm starts from right and move towards left.</p> <img src="//techcodeview.com/img/ds-tutorial/75/quick-sort-algorithm-3.webp" alt="Quick Sort Algorithm"> <p>Now, a[pivot] <a[right], so algorithm moves forward one position towards left, i.e. -< p> <img src="//techcodeview.com/img/ds-tutorial/75/quick-sort-algorithm-4.webp" alt="Quick Sort Algorithm"> <p>Now, a[left] = 24, a[right] = 19, and a[pivot] = 24.</p> <p>Because, a[pivot] &gt; a[right], so, algorithm will swap a[pivot] with a[right], and pivot moves to right, as -</p> <img src="//techcodeview.com/img/ds-tutorial/75/quick-sort-algorithm-5.webp" alt="Quick Sort Algorithm"> <p>Now, a[left] = 19, a[right] = 24, and a[pivot] = 24. Since, pivot is at right, so algorithm starts from left and moves to right.</p> <p>As a[pivot] &gt; a[left], so algorithm moves one position to right as -</p> <img src="//techcodeview.com/img/ds-tutorial/75/quick-sort-algorithm-6.webp" alt="Quick Sort Algorithm"> <p>Now, a[left] = 9, a[right] = 24, and a[pivot] = 24. As a[pivot] &gt; a[left], so algorithm moves one position to right as -</p> <img src="//techcodeview.com/img/ds-tutorial/75/quick-sort-algorithm-7.webp" alt="Quick Sort Algorithm"> <p>Now, a[left] = 29, a[right] = 24, and a[pivot] = 24. As a[pivot] <a[left], so, swap a[pivot] and a[left], now pivot is at left, i.e. -< p> <img src="//techcodeview.com/img/ds-tutorial/75/quick-sort-algorithm-8.webp" alt="Quick Sort Algorithm"> <p>Since, pivot is at left, so algorithm starts from right, and move to left. Now, a[left] = 24, a[right] = 29, and a[pivot] = 24. As a[pivot] <a[right], so algorithm moves one position to left, as -< p> <img src="//techcodeview.com/img/ds-tutorial/75/quick-sort-algorithm-9.webp" alt="Quick Sort Algorithm"> <p>Now, a[pivot] = 24, a[left] = 24, and a[right] = 14. As a[pivot] &gt; a[right], so, swap a[pivot] and a[right], now pivot is at right, i.e. -</p> <img src="//techcodeview.com/img/ds-tutorial/75/quick-sort-algorithm-10.webp" alt="Quick Sort Algorithm"> <p>Now, a[pivot] = 24, a[left] = 14, and a[right] = 24. Pivot is at right, so the algorithm starts from left and move to right.</p> <img src="//techcodeview.com/img/ds-tutorial/75/quick-sort-algorithm-11.webp" alt="Quick Sort Algorithm"> <p>Now, a[pivot] = 24, a[left] = 24, and a[right] = 24. So, pivot, left and right are pointing the same element. It represents the termination of procedure.</p> <p>Element 24, which is the pivot element is placed at its exact position.</p> <p>Elements that are right side of element 24 are greater than it, and the elements that are left side of element 24 are smaller than it.</p> <img src="//techcodeview.com/img/ds-tutorial/75/quick-sort-algorithm-12.webp" alt="Quick Sort Algorithm"> <p>Now, in a similar manner, quick sort algorithm is separately applied to the left and right sub-arrays. After sorting gets done, the array will be -</p> <img src="//techcodeview.com/img/ds-tutorial/75/quick-sort-algorithm-13.webp" alt="Quick Sort Algorithm"> <h2>Quicksort complexity</h2> <p>Now, let&apos;s see the time complexity of quicksort in best case, average case, and in worst case. We will also see the space complexity of quicksort.</p> <h3>1. Time Complexity</h3> <table class="table"> <tr> <th>Case</th> <th>Time Complexity</th> </tr> <tr> <td> <strong>Best Case</strong> </td> <td>O(n*logn)</td> </tr> <tr> <td> <strong>Average Case</strong> </td> <td>O(n*logn)</td> </tr> <tr> <td> <strong>Worst Case</strong> </td> <td>O(n<sup>2</sup>)</td> </tr> </table> <ul> <tr><td>Best Case Complexity -</td> In Quicksort, the best-case occurs when the pivot element is the middle element or near to the middle element. The best-case time complexity of quicksort is <strong>O(n*logn)</strong> . </tr><tr><td>Average Case Complexity -</td> It occurs when the array elements are in jumbled order that is not properly ascending and not properly descending. The average case time complexity of quicksort is <strong>O(n*logn)</strong> . </tr><tr><td>Worst Case Complexity -</td> In quick sort, worst case occurs when the pivot element is either greatest or smallest element. Suppose, if the pivot element is always the last element of the array, the worst case would occur when the given array is sorted already in ascending or descending order. The worst-case time complexity of quicksort is <strong>O(n<sup>2</sup>)</strong> . </tr></ul> <p>Though the worst-case complexity of quicksort is more than other sorting algorithms such as <strong>Merge sort</strong> and <strong>Heap sort</strong> , still it is faster in practice. Worst case in quick sort rarely occurs because by changing the choice of pivot, it can be implemented in different ways. Worst case in quicksort can be avoided by choosing the right pivot element.</p> <h3>2. Space Complexity</h3> <table class="table"> <tr> <td> <strong>Space Complexity</strong> </td> <td>O(n*logn)</td> </tr> <tr> <td> <strong>Stable</strong> </td> <td>NO</td> </tr> </table> <ul> <li>The space complexity of quicksort is O(n*logn).</li> </ul> <h2>Implementation of quicksort</h2> <p>Now, let&apos;s see the programs of quicksort in different programming languages.</p> <p> <strong>Program:</strong> Write a program to implement quicksort in C language.</p> <pre> #include /* function that consider last element as pivot, place the pivot at its exact position, and place smaller elements to left of pivot and greater elements to right of pivot. */ int partition (int a[], int start, int end) { int pivot = a[end]; // pivot element int i = (start - 1); for (int j = start; j <= 27 end - 1; j++) { if current element is smaller than the pivot (a[j] < pivot) i++; increment index of int t="a[i];" a[i]="a[j];" a[j]="t;" } a[i+1]="a[end];" a[end]="t;" return (i + 1); * function to implement quick sort void quick(int a[], start, end) a[]="array" be sorted, start="Starting" index, (start p="partition(a," end); partitioning quick(a, 1, print an array printarr(int n) i; for i n; i++) printf('%d ', a[i]); main() 24, 9, 29, 14, 19, }; n="sizeof(a)" sizeof(a[0]); printf('before sorting elements are 
'); printarr(a, n); 0, printf('
after 0; pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/ds-tutorial/75/quick-sort-algorithm-14.webp" alt="Quick Sort Algorithm"> <p> <strong>Program:</strong> Write a program to implement quick sort in C++ language.</p> <pre> #include using namespace std; /* function that consider last element as pivot, place the pivot at its exact position, and place smaller elements to left of pivot and greater elements to right of pivot. */ int partition (int a[], int start, int end) { int pivot = a[end]; // pivot element int i = (start - 1); for (int j = start; j <= 26 end - 1; j++) { if current element is smaller than the pivot (a[j] < pivot) i++; increment index of int t="a[i];" a[i]="a[j];" a[j]="t;" } a[i+1]="a[end];" a[end]="t;" return (i + 1); * function to implement quick sort void quick(int a[], start, end) a[]="array" be sorted, start="Starting" index, (start p="partition(a," end); partitioning quick(a, 1, print an array printarr(int n) i; for i n; i++) cout< <a[i]<< ' '; main() 23, 8, 28, 13, 18, }; n="sizeof(a)" sizeof(a[0]); cout<<'before sorting elements are 
'; printarr(a, n); 0, cout<<'
after 0; pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/ds-tutorial/75/quick-sort-algorithm-15.webp" alt="Quick Sort Algorithm"> <p> <strong>Program:</strong> Write a program to implement quicksort in python.</p> <pre> #function that consider last element as pivot, #place the pivot at its exact position, and place #smaller elements to left of pivot and greater #elements to right of pivot. def partition (a, start, end): i = (start - 1) pivot = a[end] # pivot element for j in range(start, end): # If current element is smaller than or equal to the pivot if (a[j] <= 1 pivot): i="i" + a[i], a[j]="a[j]," a[i] a[i+1], a[end]="a[end]," a[i+1] return (i 1) # function to implement quick sort def quick(a, start, end): a[]="array" be sorted, start="Starting" index, end="Ending" index if (start < p="partition(a," end) is partitioning - 1, printarr(a): print the array for in range(len(a)): (a[i], ) a="[68," 13, 49, 58] print('before sorting elements are ') printarr(a) 0, len(a)-1) print('
after pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/ds-tutorial/75/quick-sort-algorithm-16.webp" alt="Quick Sort Algorithm"> <p> <strong>Program:</strong> Write a program to implement quicksort in Java.</p> <pre> public class Quick { /* function that consider last element as pivot, place the pivot at its exact position, and place smaller elements to left of pivot and greater elements to right of pivot. */ int partition (int a[], int start, int end) { int pivot = a[end]; // pivot element int i = (start - 1); for (int j = start; j <= 25 end - 1; j++) { if current element is smaller than the pivot (a[j] < pivot) i++; increment index of int t="a[i];" a[i]="a[j];" a[j]="t;" } a[i+1]="a[end];" a[end]="t;" return (i + 1); * function to implement quick sort void quick(int a[], start, end) a[]="array" be sorted, start="Starting" index, (start p="partition(a," end); partitioning quick(a, 1, print an array printarr(int n) i; for i n; i++) system.out.print(a[i] ' '); public static main(string[] args) 13, 18, 27, 2, 19, }; n="a.length;" system.out.println('
before sorting elements are q1="new" quick(); q1.printarr(a, n); q1.quick(a, 0, system.out.println('
after system.out.println(); pre> <p> <strong>Output</strong> </p> <p>After the execution of above code, the output will be -</p> <img src="//techcodeview.com/img/ds-tutorial/75/quick-sort-algorithm-17.webp" alt="Quick Sort Algorithm"> <p> <strong>Program:</strong> Write a program to implement quick sort in php.</p> <pre> <?php /* function that consider last element as pivot, place the pivot at its exact position, and place smaller elements to left of pivot and greater elements to right of pivot. */ function partition (&$a, $start, $end) { $pivot = $a[$end]; // pivot element $i = ($start - 1); for ($j = $start; $j <= $end - 1; $j++) { // If current element is smaller than the pivot if ($a[$j] < $pivot) { $i++; // increment index of smaller element $t = $a[$i]; $a[$i] = $a[$j]; $a[$j] = $t; } } $t = $a[$i+1]; $a[$i+1] = $a[$end]; $a[$end] = $t; return ($i + 1); } /* function to implement quick sort */ function quick(&$a, $start, $end) /* a[] = array to be sorted, start = Starting index, end = Ending index */ { if ($start < $end) { $p = partition($a, $start, $end); //p is partitioning index quick($a, $start, $p - 1); quick($a, $p + 1, $end); } } function printArray($a, $n) { for($i = 0; $i < $n; $i++) { print_r($a[$i]); echo ' '; } } $a = array( 89, 47, 2, 17, 8, 19 ); $n = count($a); echo 'Before sorting array elements are - <br>&apos;; printArray($a, $n); quick($a, 0, $n - 1); echo &apos; <br> After sorting array elements are - <br>&apos;; printArray($a, $n); ?&gt; </pre> <p> <strong>Output</strong> </p> <p>After the execution of above code, the output will be -</p> <img src="//techcodeview.com/img/ds-tutorial/75/quick-sort-algorithm-18.webp" alt="Quick Sort Algorithm"> <p>So, that&apos;s all about the article. Hope the article will be helpful and informative to you.</p> <p>This article was not only limited to the algorithm. Along with the algorithm, we have also discussed the quick sort complexity, working, and implementation in different programming languages.</p> <hr></=></pre></=></pre></=></pre></=></pre></a[right],></p></a[left],></p></a[right],></p></pivot)></pre></end)>

Sortida

alfabet numerat

Després de l'execució del codi anterior, la sortida serà -

Algoritme d'ordenació ràpida

Per tant, això és tot sobre l'article. Espero que l'article us sigui útil i informatiu.

Aquest article no es limitava només a l'algorisme. Juntament amb l'algorisme, també hem parlat de la complexitat de l'ordenació ràpida, el funcionament i la implementació en diferents llenguatges de programació.