Thursday, February 23, 2012

Technique: Quick sort animation

    First round quick sort step by step animation, for the programming beginners to get a better understanding of quick sort algorithm.(Click snail button to start animation and click it again to go back to the first page)



Cost: O(nlogn)
Worst case: O(n^2)
Best case: O(nlogn)

Quick sort code in C++:

void quickSort(int arr[], int left, int right) {
      int i = left, j = right;
      int temp;
      int pivot = arr[(left + right) / 2];

      /* partition */
      while (i <= j) {
            while (arr[i] < pivot)
                  i++;
            while (arr[j] > pivot)
                  j--;
            if (i <= j) {
                  temp = arr[i];
                  arr[i] = arr[j];
                  arr[j] = temp;
                  i++;
                  j--;
            }
      };

      /* recursion */
      if (left < j)
            quickSort(arr, left, j);
      if (i < right)
            quickSort(arr, i, right);
}



More technique animations:

Heap Sort
Binary Search
Merge Sort 
Bubble Sort 
Selection Sort 

No comments:

Post a Comment