Computer Science‎ > ‎

Arrays and Sorting: Quick Sort (C Program/Java Program source code; a tutorial and an MCQ Quiz )


A few recommendations for Data Structures and Algorithms:

Basic Sorting and Searching Algorithms for Arrays, at a glance




To go through the C program / source-code, scroll down to the end of this page

Quick Sort


Quick Sort is divide and conquer algorithm like Merge Sort. Unlike Merge Sort this does not require extra space. So it sorts in place. Here dividing step is to chose a pivot and partition the array such that all elements less than or equal to pivot are to the left of it and all the elements which are greater than or equal to the pivot are to the right of it. Recursively sort the left and right parts.

Algorithm (described in detail in the document for this tutorial)


The key to the algorithm is the partition procedure.
A 'partition' element is chosen. All elements less than the partition are put in the left half of the array, all elements greater than the partition are placed in the right half of the array.
The two halves are sorted independently and recursively.


Property:


1. Best case performance – When the partitioning produces two regions of size n/2 (where,
n is the total number of elements in the list) O(nlgn).
2. Worst case performance - When the partitioning produces one region of size n-1 (where,
n is the total number of elements in the list) and other of size 1 O(n2).
3. Average case – O(n(lgn))
4. It is not stable and uses O(lg(n)) extra space in the worst case.

Complete tutorial document with examples :



                                                                                                                                   Books from Amazon which might interest you !
 
 

Quick Sort - C Program Source Code


#include<stdio.h>
/* Logic: This is divide and conquer algorithm like Merge Sort. Unlike Merge Sort this does not require
          extra space. So it sorts in place. Here dividing step is chose a pivot and parition the array
          such that all elements less than or equal to pivot are to the left of it andd all the elements  
          which  are greater than or equal to the pivot are to the right of it. Recursivley sort the left
          and right parts.
*/


void QuickSort(int *array, int from, int to)
{
        if(from>=to)return;
        int pivot = array[from]; /*Pivot I am chosing is the starting element */
        /*Here i and j are such that in the array all elemnts a[from+1...i] are less than pivot,
          all elements a[i+1...j] are greater than pivot and the elements a[j+1...to] are which
          we have not seen which is like shown below.
          ________________________i_________________j___________
          |pivot|....<=pivot......|....>=pivot......|.........|
          If the new element we encounter than >=pivot the above variant is still satisfied.
          If it is less than pivot we swap a[j] with a[i+1].
         */

        int i = from, j, temp;
        for(j = from + 1;j <= to;j++)
        {
                if(array[j] < pivot)
                {
                        i = i + 1;
                        temp = array[i];
                        array[i] = array[j];
                        array[j] = temp;
                }
        }
        /* Finally The picture is like shown below
          _______________________i____________________
          |pivot|....<=pivot......|....>=pivot......|
        */

        temp = array[i];
        array[i] = array[from];
        array[from] = temp;
        /* So we the array is now
          ____________________i______________________
          |...<=pivot......|pivot|....>=pivot......|
        */

        /*Recursively sort the two sub arrays */
        QuickSort(array,from,i-1);
        QuickSort(array,i+1,to);
}
int main()
{
        int number_of_elements;
        scanf("%d",&number_of_elements);
        int array[number_of_elements];
        int iter;
        for(iter = 0;iter < number_of_elements;iter++)
        {
                scanf("%d",&array[iter]);
        }
        /* Calling this functions sorts the array */
        QuickSort(array,0,number_of_elements-1);
        for(iter = 0;iter < number_of_elements;iter++)
        {
                printf("%d ",array[iter]);
        }
        printf("\n");
        return 0;
}


Quick Sort - Java Program Source Code

Post to LiveJournal
/* Logic: This is divide and conquer algorithm like Merge Sort. Unlike Merge Sort this does not require
          extra space. So it sorts in place. Here dividing step is chose a pivot and parition the array
          such that all elements less than or equal to pivot are to the left of it andd all the elements  
          which  are greater than or equal to the pivot are to the right of it. Recursivley sort the left 
          and right parts.
*/
import java.io.*;
class QuickSort
{
void QuickSort(int array[], int from, int to)
{
        if(from>=to)return;
        int pivot = array[from]; /*Pivot I am chosing is the starting element */
        /*Here i and j are such that in the array all elemnts a[from+1...i] are less than pivot,
          all elements a[i+1...j] are greater than pivot and the elements a[j+1...to] are which 
          we have not seen which is like shown below.
          ________________________i_________________j___________
          |pivot|....<=pivot......|....>=pivot......|.........|
          If the new element we encounter than >=pivot the above variant is still satisfied.
          If it is less than pivot we swap a[j] with a[i+1].
         */
        int i = from, j, temp;
        for(j = from + 1;j <= to;j++)
        {
                if(array[j] < pivot) 
                {
                        i = i + 1;
                        temp = array[i];
                        array[i] = array[j];
                        array[j] = temp;
                }
        }
        /* Finally The picture is like shown below
          _______________________i____________________
          |pivot|....<=pivot......|....>=pivot......|
        */
        temp = array[i];
        array[i] = array[from];
        array[from] = temp;
        /* So we the array is now 
          ____________________i______________________
          |...<=pivot......|pivot|....>=pivot......|
        */
        /*Recursively sort the two sub arrays */
        QuickSort(array,from,i-1);
        QuickSort(array,i+1,to);
}
int main()throws IOException
{
    BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
        int number_of_elements;
        System.out.println("Enter the number of elements");
        number_of_elements=Integer.parseInt(in.readLine());
        int array[]=new int[number_of_elements]; 
        int iter;
        System.out.println("Enter the elements one by one");
        for(iter = 0;iter < number_of_elements;iter++)
        {
                array[iter]=Integer.parseInt(in.readLine());        }
        /* Calling this functions sorts the array */
        QuickSort(array,0,number_of_elements-1); 
        for(iter = 0;iter < number_of_elements;iter++)
        {
               System.out.print(array[iter]+"\t");
        }
        System.out.print("\n");
        return 0;
}
}


MCQ Quiz: Efficient Sorting Algorithms- Quick sort, Merge Sort, Heap Sort- Check how much you can score!

Your score will be e-mailed to the address filled up by you.

MCQ Quiz- More efficient sorting algorithms

Related Tutorials :

Bubble Sort    

One of the most elementary sorting algorithms to implement - and also very inefficient. Runs in quadratic time. A good starting point to understand sorting in general, before moving on to more advanced techniques and algorithms. A general idea of how the algorithm works and a the code for a C program.

Insertion Sort

Another quadratic time sorting algorithm - an example of dynamic programming. An explanation and step through of how the algorithm works, as well as the source code for a C program which performs insertion sort. 

Selection Sort

Another quadratic time sorting algorithm - an example of a greedy algorithm. An explanation and step through of how the algorithm works, as well as the source code for a C program which performs selection sort. 

 Shell Sort

An inefficient but interesting algorithm, the complexity of which is not exactly known.

Merge Sort 

An example of a Divide and Conquer algorithm. Works in O(n log n) time. The memory complexity for this is a bit of a disadvantage.

Quick Sort

In the average case, this works in O(n log n) time. No additional memory overhead - so this is better than merge sort in this regard. A partition element is selected, the array is restructured such that all elements greater or less than the partition are on opposite sides of the partition. These two parts of the array are then sorted recursively.

Heap Sort

 Efficient sorting algorithm which runs in O(n log n) time. Uses the Heap data structure. 

Binary Search Algorithm

 Commonly used algorithm used to find the position of an element in a sorted array. Runs in O(log n) time. 




Visualizing Quick Sort ( A Java Applet Visualization ) :


Here's a Java Applet Visualization which might give you a more 'colorful' idea of what happens in Quick Sort.


Click here, or on the image beloq to check out a Quick Sort Algorithm - Java Applet Visualization




http://www.thelearningpoint.net/computer-science/sorting-algorithms/quick-sort

 

Testing Zone For Programmers- 

 

Try out our online Multiple-Choice-Question tests in Programming and Computer Science!


 

Photo-credits: www.istockphoto.com

 
 Quizzes on Basic Object Oriented Programming with C++   Quizzes on Java Programming
  
 Quizzes on C Programming- Arrays, Strings and Pointers
  1. C Programming MCQ Quiz #1:  Strings- 1
  2. C Programming MCQ Quiz #2: Strings (2)
  3. C Programming MCQ Quiz #3: Strings (3)
  4. C Programming MCQ Quiz #4: Arrays(1)
  5. C Programming MCQ Quiz #5: Arrays (2)
  6. C Programming MCQ Quiz #6: Arrays (3)
  7. C Programming MCQ Quiz #7: Pointers (1)
  8. C Programming MCQ Quiz #8: Pointers (2)
 Quizzes on Data Structures, Algorithms and Complexity
  1. MCQ Quiz #1: The Basics of Sorting Algorithms- Quadratic Sorts
  2. MCQ Quiz #2: Efficient Sorting Algorithms- Quick sort, Merge Sort, Heap Sort
  3. MCQ Quiz #3- The Radix Sort
  4. MCQ Quiz #4: Divide and Conquer Techniques- Binary Search, Quicksort, Merge sort, Complexities
  5. MCQ Quiz #5- Dynamic Programming
  6. MCQ Quiz #6- Complexity of Algorithms
  7. MCQ Quiz #7- Application of Master's Theorem
  8. MCQ Quiz #8: Binary Search Trees
  9. MCQ Quiz #9: B-Trees
  10. 10 MCQ Quiz #9: AVL-Trees
  11. 11 MCQ Quiz #10: Representing Graphs as Data Structures
  12. 12 MCQ Quiz #11: Spanning Trees
  13. 13 MCQ Quiz #12: Algorithms - Graphs: Spanning Trees - Kruskal and Prim Algorithms
  14. 14 MCQ Quiz #13: Algorithms - Graphs: Depth and Breadth First Search