当前位置:网站首页>Quick sorting, simple and easy to understand principle description, with C code implementation,

Quick sorting, simple and easy to understand principle description, with C code implementation,

2022-06-21 10:28:00 ah_ yl

Quick sorting is a practical algorithm in sorting ;

The principle of fast platoon is :( From the Small To Big Sort array arr[N] For example )

1、 First find an element in the array as the anchor point ( Suppose it is the first element in the array arr[0])

2、 Traversal array Will be less than the number of anchor points ( hypothesis k A little bit ) Before array , Exchange these numbers to arr[1]~arr[k];

3、 Swap anchor points arr[0] and arr[k], here arr[k] The number before the value at position is smaller than it , The latter numbers are bigger than it ;

4、 And then the array [ arr[0],arr[k-1] ),( arr[k+1],arr[N] ] These two arrays are then recursively operated as described above

5、 Recurse until the left element subscript is greater than or equal to the right element subscript , Sort stop

C The language implementation is as follows ;

//c The core code of the language is as follows ;
void qsort(int v[],int left,int right)
{
    int i,pos;
    if (left >= right)
        return;
    // Take the first element as the anchor point 
    pos = left;
    // Traversal array , Will be less than the number of anchor points swap To the front of the array 
    for (i=left+1;i<=right;++i) {
    	if (v[i]<v[left])
            swap(v,i,++pos);
    }
    // Compare the number of anchor points with swap To its correct position pos;
    swap(v,left,pos);
    // Recurs the process 
    qsort(v,left,pos-1);
    qsort(v,pos+1,right);
}

// among swap To exchange an array with the subscript i and j Function of ;
void swap(int v[],int i,int j)
{
    int temp;
    temp = v[i];
    v[i] = v[j];
    v[j] = temp; 
}

//
int main()
{
    int arr[10] = {7,1,3,9,2,6,1,7,3,5};
    qsort(arr,0,9);
    return 0;
}

原网站

版权声明
本文为[ah_ yl]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202221443018060.html