Commonly used sorting algorithm (7)-quick sort

Quick sorting
1. Pick a number as the benchmark (here, take the number on the far right as the benchmark)
2. Put the numbers that are less than the benchmark and swap positions from the far left.
3. Then put the benchmark to the last position on the leftmost side.
4. After finishing the row on the left side of the benchmark, row on the right side

Sorting method Average situation Best case Worst case Auxiliary space stability
Quick sort O (nlogn) O (nlogn) O (n²) O (nlogn) ~ O (n) Unstable

qt code

#include "widget.h"
#include <QApplication>
#include <QtDebug>

int array[10] = {
    
    7,1,5,8,3,9,6,0,2,4};

void printArry()
{
    
    
    QString str;
    for(int i = 0; i < sizeof(array)/sizeof(int); i++ )
    {
    
    
        str += QString::number(array[i]) + " ";
    }
    qDebug() << str;
}

void swap(int array[],int i, int j)
{
    
    
    int temp = array[i];
    array[i] = array[j];
    array[j] = temp;
    printArry();
}

int partition(int array[], int left, int right)
{
    
    
    int pivot = array[right];
    int tail = left - 1;
    for(int i = left; i < right; i++)
    {
    
    
        if(array[i] <= pivot)
        {
    
    
            swap(array,++tail,i);
        }
    }
    swap(array,tail + 1,right);
    return tail + 1;
}

void quickSort(int array[], int left, int right)
{
    
    
    if(left > right)
        return;
    int j = partition(array,left,right);
    quickSort(array,left,j-1);
    quickSort(array,j+1,right);
}

int main(int argc, char *argv[])
{
    
    
    QApplication a(argc, argv);
    int n = sizeof(array)/sizeof(int);
    quickSort(array,0,n-1);
    return a.exec();
}

Output result:

数据:
"7 1 5 8 3 9 6 0 2 4 "
排序过程:
"1 7 5 8 3 9 6 0 2 4 "
"1 3 5 8 7 9 6 0 2 4 "
"1 3 0 8 7 9 6 5 2 4 "
"1 3 0 2 7 9 6 5 8 4 "
"1 3 0 2 4 9 6 5 8 7 "
"1 3 0 2 4 9 6 5 8 7 "
"1 0 3 2 4 9 6 5 8 7 "
"1 0 2 3 4 9 6 5 8 7 "
"0 1 2 3 4 9 6 5 8 7 "
"0 1 2 3 4 9 6 5 8 7 "
"0 1 2 3 4 9 6 5 8 7 "
"0 1 2 3 4 6 9 5 8 7 "
"0 1 2 3 4 6 5 9 8 7 "
"0 1 2 3 4 6 5 7 8 9 "
"0 1 2 3 4 5 6 7 8 9 "
"0 1 2 3 4 5 6 7 8 9 "
"0 1 2 3 4 5 6 7 8 9 "
"0 1 2 3 4 5 6 7 8 9 "
"0 1 2 3 4 5 6 7 8 9 "

Reference: http://www.cnblogs.com/eniac12/p/5329396.html#s1

Guess you like

Origin blog.csdn.net/sinat_33859977/article/details/100046080