Wu Yuxiong - born natural data structure: Ten classic sort algorithm - Quick Sort

Quick Sort 
Quick sort is a sorting algorithm developed by the Tony Hoare's. Under average conditions, to sort n items to Ο (nlogn) compare times. In the worst situation you need to Ο (n2) comparisons, but this situation is not uncommon. In fact, quick sort it is usually significantly higher than other Ο (nlogn) algorithm is faster because its inner loop (inner loop) can be implemented very efficiently out on most of the architecture. 

Quick sort using a divide and conquer (Divide and Conquer) strategy to put a serial (list) is divided into two sub-serial (Sub- Lists). 

Quick Sort is a typical apply a divide and conquer thoughts on sorting algorithms. Essentially, quick sort should be bubbling recursive divide and conquer on the basis of the sort. 

Quick sort of name from is simple and crude, as heard the name you will know the meaning of its existence, that is, fast, and efficient! It is one of the big data processing fastest sorting algorithm of. 
In the "algorithm of Art and Informatics Contest": worst-case run quick sort is O (n²), for example, fast row order number sequence. However, it is desirable amortized time is O (nlogn), and O (nlogn) notation implies a small constant factor, equal complexity than stable O (nlogn) merge sort is much smaller. So, the vast majority of the order of weak random number sequence, the quick sort is always better than merge sort. 
1 . Algorithm steps 
pick out the number of columns in an element, called a " reference " (Pivot); 

reordering columns, all of the elements placed in front of the reference small than the reference value, the reference value is larger than all of the elements placed at the back of the reference (the same number can be either side). After the partition exit, on the basis of the number of columns in the middle position. This is called a partition (Partition) operation;

Recursively (recursive This) than the reference value the number of columns and the sub-element is greater than the reference value of the child element of the sorted columns;
代码实现
JavaScript
function quickSort(arr, left, right) {
    var len = arr.length,
        partitionIndex,
        left = typeof left != 'number' ? 0 : left,
        right = typeof right != 'number' ? len - 1 : right;

    if (left < right) {
        partitionIndex = partition(arr, left, right);
        quickSort(arr, left, partitionIndex-1);
        quickSort(arr, partitionIndex+1, right);
    }
    return arr;
}

function partition(arr, left ,right) {     // 分区操作
    var pivot = left,                      // 设定基准值(pivot)
        index = pivot + 1;
    for (var i = index; i <= right; i++) {
        if (arr[i] < arr[pivot]) {
            swap(arr, i, index);
            index++;
        }        
    }
    swap(arr, pivot, index - 1);
    return index-1;
}

function swap(arr, i, j) {
    var temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}
function partition2(arr, low, high) {
  let pivot = arr[low];
  while (low < high) {
    while (low < high && arr[high] > pivot) {
      --high;
    }
    arr[low] = arr[high];
    while (low < high && arr[low] <= pivot) {
      ++low;
    }
    arr[high] = arr[low];
  }
  arr[low] = pivot;
  return low;
}

function quickSort2(arr, low, high) {
  if (low < high) {
    let pivot = partition2(arr, low, high);
    quickSort2(arr, low, pivot - 1);
    quickSort2(arr, pivot + 1, high);
  }
  return arr;
}
Python
def quickSort(arr, left=None, right=None):
    left = 0 if not isinstance(left,(int, float)) else left
    right = len(arr)-1 if not isinstance(right,(int, float)) else right
    if left < right:
        partitionIndex = partition(arr, left, right)
        quickSort(arr, left, partitionIndex-1)
        quickSort(arr, partitionIndex+1, right)
    return arr

def partition(arr, left, right):
    pivot = left
    index = pivot+1
    i = index
    while  i <= right:
        if arr[i] < arr[pivot]:
            swap(arr, i, index)
            index+=1
        i+=1
    swap(arr,pivot,index-1)
    return index-1

def swap(arr, i, j):
    arr[i], arr[j] = arr[j], arr[i]
Go
func quickSort(arr []int) []int {
        return _quickSort(arr, 0, len(arr)-1)
}

func _quickSort(arr []int, left, right int) []int {
        if left < right {
                partitionIndex := partition(arr, left, right)
                _quickSort(arr, left, partitionIndex-1)
                _quickSort(arr, partitionIndex+1, right)
        }
        return arr
}

func partition(arr []int, left, right int) int {
        pivot := left
        index := pivot + 1

        for i := index; i <= right; i++ {
                if arr[i] < arr[pivot] {
                        swap(arr, i, index)
                        index += 1
                }
        }
        swap(arr, pivot, index-1)
        return index - 1
}

func swap(arr []int, i, j int) {
        arr[i], arr[j] = arr[j], arr[i]
}
C++
//严蔚敏《数据结构》标准分割函数
 Paritition1(int A[], int low, int high) {
   int pivot = A[low];
   while (low < high) {
     while (low < high && A[high] >= pivot) {
       --high;
     }
     A[low] = A[high];
     while (low < high && A[low] <= pivot) {
       ++low;
     }
     A[high] = A[low];
   }
   A[low] = pivot;
   return low;
 }

 void QuickSort(int A[], int low, int high) // quick drain generating function 
 { 
   IF (Low < High) { 
     int Pivot = Paritition1 (A, Low, High); 
     the QuickSort (A, Low, Pivot -. 1 ); 
     the QuickSort (A, Pivot +. 1 , High); 
   } 
 }
Java
public class QuickSort implements IArraySort {

    @Override
    public int[] sort(int[] sourceArray) throws Exception {
        // 对 arr 进行拷贝,不改变参数内容
        int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);

        return quickSort(arr, 0, arr.length - 1);
    }

    private int[] quickSort(int[] arr, int left, int right) {
        if (left < right) {
            int partitionIndex = partition(arr, left, right);
            quickSort(arr, left, partitionIndex - 1);
            quickSort(arr, partitionIndex + 1, right);
        }
        return arr;
    }

    private int partition(int[] arr, int left, int right) {
        // 设定基准值(pivot)
        int pivot = left;
        int index = pivot + 1;
        for (int i = index; i <= right; i++) {
            if (arr[i] < arr[pivot]) {
                swap(arr, i, index);
                index++;
            }
        }
        swap(arr, pivot, index - 1);
        return index - 1;
    }

    private void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

}
PHP
function quickSort($arr)
{
    if (count($arr) <= 1)
        return $arr;
    $middle = $arr[0];
    $leftArray = array();
    $rightArray = array();

    for ($i = 1; $i < count($arr); $i++) {
        if ($arr[$i] > $middle)
            $rightArray[] = $arr[$i];
        else
            $leftArray[] = $arr[$i];
    }
    $leftArray = quickSort($leftArray);
    $leftArray[] = $middle;

    $rightArray = quickSort($rightArray);
    return array_merge($leftArray, $rightArray);
}
C 
typedef struct {_Range 
    int Start, End; 
} the Range; 

the Range new_Range (S int, int E) { 
    the Range R & lt; 
    r.start = S; 
    r.end = E;
     return R & lt; 
} 

void the swap (int * X, int * Y) { 
    int T = * X;
     * = X * Y;
     * Y = T; 
} 

void quick_sort (ARR int [], const int len) { 
    IF (len <= 0)
         return ; // avoid len equal to the negative error initiator segment (segment Fault) value
     // r [] a list of simulation, p is the number, r [p ++] as Push, R & lt [- P] is acquired and the pop element  
    Range r [len];
    int p = 0; 
    R & lt [P ++] = new_Range (0, len -. 1 );
     the while (P) { 
        the Range Range = R & lt [- P];
         IF (range.start> = range.end)
             Continue ; 
        int mID = ARR [(range.start range.end +) / 2]; // selected intermediate point as a reference point 
        int left = range.start, right = range.end; 
        do { 
            the while (ARR [left] <mID) + + left; // left detection reference point meets the requirements
             the while (ARR [right]> MID) --right; // right detection reference point meets the requirements
             iF (left <= right) { 
                the swap (&arr[left], &arr[right]);
                left++;
                right--;               // 移動指針以繼續
            }
        } while (left <= right);
        if (range.start < right) r[p++] = new_Range(range.start, right);
        if (range.end > left) r[p++] = new_Range(left, range.end);
    }
}
递归法
void swap(int *x, int *y) {
    int t = *x;
    *x = *y;
    *y = t;
}

void quick_sort_recursive(int arr[], int start, int end) {
    if (start >= end)
        return;
    int mid = arr[end];
    int left = start, right = end - 1;
    while (left < right) {
        while (arr[left] < mid && left < right)
            left++;
        while (arr[right] >= mid && left < right)
            right--;
        swap(&arr[left], &arr[right]);
    }
    if (arr[left] >= arr[end])
        swap(&arr[left], &arr[end]);
    else
        left++;
    if (left)
        quick_sort_recursive(arr, start, left - 1);
    quick_sort_recursive(arr, left + 1, end);
}

void quick_sort(int arr[], int len) {
    quick_sort_recursive(arr, 0, len - 1);
}
C ++ 
function method 
Sort (A, A + n-); // Sort a [0] -a [n- 1 number of all] the. 
Iterative method 
struct the Range { 
    int Start, End; 
    the Range (int S = 0, E = int 0) { 
        Start = S, End = E; 
    } 
}; 
Template <typename T> // integer or floating point can be used, to use the object ( class must setting) " is less than " (<), " greater than " (>), " not less than " (> = ) the operator function 
void quick_sort (ARR T [], const int len) { 
    iF (len <= 0)
         return ; // avoid len is equal to a negative value when stacked array declaration machine
    // r[]模擬堆疊,p為數量,r[p++]為push,r[--p]為pop且取得元素
    Range r[len];
    int p = 0;
    r[p++] = Range(0, len - 1);
    while (p) {
        Range range = r[--p];
        if (range.start >= range.end)
            continue;
        T mid = arr[range.end];
        int left = range.start, right = range.end - 1;
        while (left < right) {
            while (arr[left] < mid && left < right) left++;
            while (arr[right] >= mid && left < right) right--;
            std::swap(arr[left], arr[right]);
        }
        if (arr[left] >= arr[range.end])
            std::swap(arr[left], arr[range.end]);
        else
            left++;
        r[p++] = Range(range.start, left - 1);
        r[p++] = Range(left + 1, range.end);
    }
}
递归法
template <typename T>
void quick_sort_recursive(T arr[], int start, int end) {
    if (start >= end)
        return;
    T mid =ARR [End]; 
    int left = Start, End = right -. 1 ;
     the while (left <right) {// search hub membered values than small or large elements in full, then the left element and right element exchange
         the while (ARR [left] <MID && left <right) // try to find a larger element than in the left side of the hub element 
            left ++ ;
         the while (ARR [right]> MID = && left <right) // attempt find a right element is smaller than the hub element 
            right - ; 
        STD :: the swap (ARR [left], ARR [right]); // switching element 
    } 
    IF (ARR [left]> = ARR [End]) 
        STD the swap :: (ARR [left], ARR [End]); 
    the else 
        left ++ ;
    quick_sort_recursive (ARR, Start, left -. 1 ); 
    quick_sort_recursive (ARR, left +. 1 , End); 
} 
Template <typename T> // integer or floating point can be used, to use the object ( class must setting) " less than " (<), " greater than " (>), " not less than " (> = ) the operator function 
void quick_sort (ARR T [], int len) { 
    quick_sort_recursive (ARR, 0, len -. 1 ); 
}

 

Guess you like

Origin www.cnblogs.com/tszr/p/11973779.html