ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

easy quicksort tutorial with Java/C/C++ examples

Updated on August 2, 2010

What's the Quicksort?

Quicksort is a fast and reliable method of sorting data, the quicksort (without any kind of refinaments) is very simple to write but it still is a very fast sorting algorithm compared to other algorithms such as the bubblesort.

In the video on the right you can watch some sorting algorithms and you will see the performance of the quicksort against the other algorithms, but quicksort has its own "flaws" which are referred below.

The quicksort was invented by Charles Antony Richard Hoare in 1960

Explaining the Quicksort

  • PIVOT: The first thing that you have to do is selecting a pivot, a pivot is any number of the array that you want to sort, it can be the last, the first, the middle one, it has no criteria to be selected.

  • PARTITION: This is for me the hardest part to explain and to understand, so i'll try to be clear enough. Think in a partition like an array, in this array you will start with a pointer at the beginning (the i), and with one pointer at the end (the j).

What you will do with the i is travel through the array forward until you find an element that is equal or greater than the pivot.

With the j you will travel through the array backward until you find an element that is equal or smaller than the pivot.

while (i <= j) 
{
   while (arr[i] < pivot)
      i++;           
	
   while (arr[j] > pivot)
      j--;	       
//continue...

Then after you found both numbers, you will swap them only if this condition "i<=j" is true, which means that the two pointers haven't met or crossed each other yet, so there are some numbers left to analyze.

//...continuation   
   if (i <= j) 
   {
      tmp = arr[i];
      arr[i] = arr[j];
      arr[j] = tmp;
      i++;
      j--;
   }
};
example of how the partition method works
example of how the partition method works

After you have done this, you will realize that you have your array divided in two non-equal parts, left with numbers equal or smaller than the pivot and on the right with numbers equal or greater than the pivot.

The picture on the left demonstrates what we have done so far with an example.

(click on it to get the full view)

  • RECURSION: Then recursively sort the new partition of smaller elements, and then the partition of greater elements.

if (left < j) //left is the begin of the array
   quickSort(arr, left, j);
if (i < right) //right is the end of the array
   quickSort(arr, i, right);

C/C++ Example

void quickSort(int arr[], int left, int right) {
      int i = left, j = right;
      int tmp;
      int pivot = arr[(left + right) / 2];
 
      /* partition */
      while (i <= j) {
            while (arr[i] < pivot)
                  i++;
            while (arr[j] > pivot)
                  j--;
            if (i <= j) {
                  tmp = arr[i];
                  arr[i] = arr[j];
                  arr[j] = tmp;
                  i++;
                  j--;
            }
      };
 
      /* recursion */
      if (left < j)
            quickSort(arr, left, j);
      if (i < right)
            quickSort(arr, i, right);
}

This example isn't mine but i have used it before and it works, the parameters of the method are the array, the start postion which is commonly 0, and the size of the array -1.

As far as i know you only have to take the "void" from the method and it will work for C.

(the link below will redirect you to the page where i get these code sample)

JAVA Example

static void quicksort(int array[], int begin, int end) {
    int i = begin, j = end;
    int pivot = array[end];
    while (i <= j) {
        while (array[i] < pivot)i++;
        while (array[j] > pivot)j--;
        if (i <= j) {
            if (i != j) {             //this is a swap of values
                array[i] ^= array[j]; //without a use of an extra
                array[j] ^= array[i]; //variable, it is a swap using
                array[i] ^= array[j]; //the XOR operator, i used it
            }                         //so you can learn it because i
            i++;                      //think it is fun.
            j--;
        } 
    } 
    if (begin < j)
        quicksort(array, begin, j);
    if (i < end)
        quicksort(array, i, end);
}

This JAVA example i made it myself and i use the XOR operator to do the swap, when you use the swap with arrays you must verify if the to pointers i and j are not equal because it won't work if they are equal, to understand the XOR swap better open the link below.

Quicksort "flaws"

This presented quicksort isn't perfect actually it is the quicksort on is simplest form, because it has no kind of refinement it works as fast as a bubblesort in is worst case. An example will be an array with all of it's elements of the same value. If you give 1sec of thought about it you will see for every movement of i and j you will be realizing a swap.

Review poll

What do you think about this hubpage?

See results
working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)