Quick Sort algorithm based

The core idea of the quick sort algorithm is set to a value greater than this value the right "throw" than this little value left "throw."
Quick sort of array process:

  1. Set two variables i, j, at the beginning of the sort: i = 0, j = n-1; (n is the number of sort)
  2. In the first element in the array as a comparison value, assigned to the variable key, i.e., key = a [0];
  3. First searches forward from j, i.e., back to front (-j), find the first key is less than the value a [j], the a [j] and a [i] are interchangeable;
  4. Then searches back from i, i.e., from front to back (++ i), is greater than the key to find a first value a [i], the a [i] and a [j] are interchangeable;
  5. Repeating the third and fourth steps until i is equal to j. At this point we can ensure full sequence key on the left is a value smaller than the key, the right key of all value greater than the key. Then the above steps are recursively performed on both sides, until the end of sorting.
#include <stdio.h>
void QuickSort (int *,int,int);//函数声明,快速排序//
int main(int argc,const char *argv[])
{
    int i;
    int a[]={900,2,-58,3,34,5,76,7,32,4,43,9,1,56,8,-70,635,-234,532,543,2500};
    QuickSort(a,0,20);/*引用起来很简单,0为第一个元素的下表,20为最后一个元素的下表*/
    printf("最终排序结果为:\n");
    for(i=0;i<=20;++i)
    {
        printf("%d\n",a[i]);
    }
    printf("\n");
    return 0;
}
void QuickSort(int *a,int low,int high)
{
    int i,j;
    i=low;
    j=high;
    int key=a[low];
    if(low>=high)//如果low>=high说明排序结束了
    {
        return;
    }
    while(low<high)//该while循环结束一次表示比较了一轮//
    {
        while(low<high&&key<=a[high])
        {
            --high;
        }
        if(key>a[high])
        {
            a[low]=a[high];
            ++low;
        }
        while(low<high&&key>=a[low])
        {
            ++low;
        }
        if(key<a[low])
        {
            a[high]=a[low];
            --high;
        }
        
    }
    a[low]=key;
    QuickSort(a,i,low-1);
    QuickSort(a,low+1,j);
}

Guess you like

Origin blog.csdn.net/smilezyf/article/details/92396074