C语言实现快速排序(三种)

  • Post author:
  • Post category:其他


第一种:

#include<stdio.h>

void Swap(int*a,int*b)
{
    int tmp=*a;
    *a=*b;
    *b=tmp;
}


int PartSort1(int* a, int left, int right)//快排
{
	int keyi = left;
	while (left < right)
	{
		//找小
		while (left < right && a[right] >= a[keyi])
		{
			--right;
		}

		//找大
		while (left < right && a[left] <= a[keyi])
		{
			++left;
		}
		Swap(&a[left], &a[right]);
	}
	Swap(&a[keyi], &a[left]);
	return left;
}



 void Quicksort(int*a,int begin,int end)
 {
     if(begin>=end)
     return 0;

     int key=PartSort1(a,begin,end);
     Quicksort(a,begin,key-1);
     Quicksort(a,key+1,end);
 }


int main()
{
    int a[10]={0,7,9,8,5,6,4,3,2,1};

    Quicksort(a,0,9);

    for(int i=0;i<10;i++)
    {
        printf("%d ",a[i]);
    }

    return 0;
}

第二种:挖坑法

#include<stdio.h>

void Swap(int* a, int* b)
{
    int tmp = *a;
    *a = *b;
    *b = tmp;
}


int PartSort2(int* a, int left, int right)//快排
{
    int key = a[left];
    int pit = left;
    while (left < right)
    {
        while (left<right && a[right]>key)
            right--;

        a[pit] = a[right];
        pit = right;

        while (left < right && a[left] <key)
            left++;

        a[pit] = a[left];
        pit = left;

    }
    a[pit] =key;
    return pit;

}



void Quicksort(int* a, int begin, int end)
{
    if (begin >= end)
        return 0;

    int key = PartSort2(a, begin, end);
    Quicksort(a, begin, key - 1);
    Quicksort(a, key + 1, end);
}


int main()
{
    int a[10] = { 0,7,9,8,5,6,4,3,2,1 };

    Quicksort(a, 0, 9);

    for (int i = 0; i < 10; i++)
    {
        printf("%d ", a[i]);
    }

    return 0;
}

第三种:

#include<stdio.h>

void Swap(int* a, int* b)
{
    int tmp = *a;
    *a = *b;
    *b = tmp;
}


int PartSort3(int* a, int left, int right)//快排
{
    int key = left;
    int prev = left;
    int cur = left + 1;
    while (cur <= right)
    {
        if (a[cur] < a[key]&& a[++prev] != a[cur])
            Swap(&a[prev], &a[cur]);
        cur++;
    }
    Swap(&a[prev], &a[key]);
    return prev;

}



void Quicksort(int* a, int begin, int end)
{
    if (begin >= end)
        return 0;

    int key = PartSort3(a, begin, end);
    Quicksort(a, begin, key - 1);
    Quicksort(a, key + 1, end);
}


int main()
{
    int a[10] = { 0,7,9,8,5,6,4,3,2,1 };

    Quicksort(a, 0, 9);

    for (int i = 0; i < 10; i++)
    {
        printf("%d ", a[i]);
    }

    return 0;
}



版权声明:本文为m0_62898700原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。