# QuickSort on Doubly Linked List

Following is a typical recursive implementation of QuickSort for arrays. The implementation uses last element as pivot.
 /* A typical recursive implementation of Quicksort for array*/   /* This function takes last element as pivot, places the pivot element at its    correct position in sorted array, and places all smaller (smaller than    pivot) to left of pivot and all greater elements to right of pivot */ int partition (int arr[], int l, int h) {     int x = arr[h];     int i = (l - 1);       for (int j = l; j <= h- 1; j++)     {         if (arr[j] <= x)         {             i++;             swap (&arr[i], &arr[j]);         }     }     swap (&arr[i + 1], &arr[h]);     return (i + 1); }   /* A[] --> Array to be sorted, l  --> Starting index, h  --> Ending index */ void quickSort(int A[], int l, int h) {     if (l < h)     {                int p = partition(A, l, h); /* Partitioning index */         quickSort(A, l, p - 1);          quickSort(A, p + 1, h);     } }
Can we use same algorithm for Linked List?
Following is C++ implementation for doubly linked list. The idea is simple, we first find out pointer to last node. Once we have pointer to last node, we can recursively sort the linked list using pointers to first and last nodes of linked list, similar to the above recursive function where we pass indexes of first and last array elements. The partition function for linked list is also similar to partition for arrays. Instead of returning index of the pivot element, it returns pointer to the pivot element. In the following implementation, quickSort() is just a wrapper function, the main recursive function is _quickSort() which is similar to quickSort() for array implementation.
Output :
30  3  4  20  5