快速排序

来源:互联网 发布:美国大选特朗普 知乎 编辑:程序博客网 时间:2024/05/16 18:09

快速排序算法:以a[0]为基准pivot,大于基准的放基准的右边,小于基准的放基准左边,一直递归调用,达到排序的目的。

 

代码部分(第一种方法)

void quick_sort(int a[], int start, int end)
{
        int temp = a[start];
        int mid = start;
        int i = start, j = end;
        while (i <= j)
        {
                while (a[j] >= temp && j >= mid )
                        j--;
                if(j >= mid)
                {
                        a[mid] = a[j];
                        mid = j;
                }
 
                while (a[i] <= temp && i <= mid)
                        i++;
                if (i <= mid)
                {
                        a[mid] = a[i];
                        mid = i;
                }
        }
        a[mid] = temp;
        if(mid-start > 1)
                quick_sort(a, start, mid-1);
        if(end - mid > 1)
                quick_sort(a, mid+1, end);
}

代码部分(第二种方法)

int  find_pivot(int a[],  int low,  int high)
{
  int pivotkey;
  pivotkey=a[low];
  while(low < high)
  {
    while(low < high && a[high] >= pivotkey)
    high--;
    a[low] = a[high];
    while(low < high && a[low] <= pivotkey)
    low++;
    a[high] = a[low];
  }
  a[low] = pivotkey;
  return low;
}

void  quick_sort(int a[],  int low,  int high)
{
  int pivot;
  if(low < high)
  {
    pivot=find_pivot(a, low, high);
    quick_sort(a, low, pivot-1);
    quick_sort(a, pivot+1, high);
  }
}