Data Journey

International Studies Grad. racing for AI Engineer

Download as .zip Download as .tar.gz View on GitHub
16 January 2021

Quick Sort

by mervyn

Strategy

We have seen two \(\Theta(n lg(n))\) sorting algorithms:

We will now look at a recursive algorithm which may be done almost in place but which is faster than heap sort

We will look at strategies for avoiding the worst case

Quicksort

Merge sort

Consider the following alternative:

Runtime Analysis

Like merge sort, we can either:

Median-of-Three

  1. Sorting the elements based on the middle entry results in two sub-lists, each of which must be sorted (again, using quicksort).
  2. Undergoes partitioning based on median-of-three, and find the median-of-three from those median-of-threes
  3. Starting from the front, the values smaller than the median-of-three filled in from the left. The values larger than the median-of-three filled in from the right.
  4. Once finished, copy the median-of-three into the resulting hole.

In-place Implementation

  1. Examine the first, middle, and last entries and choose the median of these to be the pivot. In addition, we can:
    • move the smallest entry to the first entry
    • move the largest entry to the middle entry
  2. Partition all remaining elements based on whether they are smaller than or greater than the pivot Find two entries:
    • One larger than the pivot (starting from the front)
    • One smaller than the pivot (starting from the back) which are out of order and then swap them
  3. Continue doing so until the appropriate entries you find are actually in order
    • The index to the larger entry we found would be the first large entry in the list (as seen from the left)
    • Therefore, we could move this entry into the last entry of the list
    • We can fill this spot with the pivot
template <typename Type>
void Quicksort(Type *_array, int _first, int _last){
  if(_last - _first <= NUM_THRESHOLD){
    Insertion_Sort<Type>(&_array[_first], _last-_first);
  }
  else{
    Type pivot = Find_Pivot<Type>(_array, _first, _last);
    int low= _first +1;
    int high= _last -2;
    while(_array[low]<pivot){low++;}
    while(_array[high]>pivot){high--;}
    while(low<high){
      std::swap(_array[low], _array[high]);
      low++; high--;
      while(_array[low]<pivot){low++;}
      while(_array[high]>pivot){high--;}
    }
    _array[_last-1] = _array[low];
    _array[low]=pivot;
    Quicksort(_array, _first, low);
    Quicksort(_array, high, _last);
  }
}

Memory Requirements

runtimesum

source “K-MOOC 허재필 교수님의 <인공지능을 위한 알고리즘과 자료구조: 이론, 코딩, 그리고 컴퓨팅 사고> 강좌의 10-2 힙 정렬 중(http://www.kmooc.kr/courses/course-v1:SKKUk+SKKU_46+2020_T1)”

back next

tags:

Comments

Post comment
Loading...

Share this: