排序练习--快排 && 归并

#include <stdio.h>
#include <stdlib.h>

void swap(int &a, int &b)
{
   int t = a;
   a = b;
   b = t;
}

void qsort1(int elem[], int start, int end)
{
   if(start >= end)
   {
       return;
   }

   int m = start;
   for(int i = start+1; i <= end; i++)
   {
       if(elem[i] <= elem[start])
       {
           swap(elem[++m], elem[i]);
       }
   }
   swap(elem[m], elem[start]);
   qsort1(elem, start, m-1);
   qsort1(elem,   m+1, end);
}


void qsort2(int elem[], int start, int end)
{
   if(start >= end)
   {
       return;
   }
   int left = start, right = end+1;
   while(1)
   {
       do{left++;}while(left <= end && elem[left] < elem[start]);
       do{right--;}while(elem[right] > elem[start]);

       if(left > right)
       {
           break;
       }
       swap(elem[left], elem[right]);
   }
   swap(elem[start], elem[right]);
   qsort2(elem, start, right-1);
   qsort2(elem, right+1, end);
}

void mergesort(int elem[],int start,int end)
{
   if(start >= end)
   {
       return;
   }
   int mid = (start+end)>>1;
   mergesort(elem,start,mid);
   mergesort(elem,mid+1,end);

   int *tmpElem = new int[end-start+1];
   int i = start, j = mid+1, k = 0;
   while(i <= mid && j <= end)
   {
       if(elem[i] < elem[j])
       {
           tmpElem[k++] = elem[i++];
       }
       else
       {
           tmpElem[k++] = elem[j++];
       }
   }
   while(i <= mid) tmpElem[k++] = elem[i++];
   while(j <= end) tmpElem[k++] = elem[j++];

   for(i = start; i <= end; i++)
   {
       elem[i] = tmpElem[i - start];
   }
   delete []tmpElem;
}
void print(int elem[],int n)
{
   for(int i = 0; i < n; i++)
   {
       printf("%d ", elem[i]);
   }
   printf("\n");
}

int main()
{
   int elem1[12] = {3,42,33,21,145,12,345,12,3,2,3,41};
   int elem2[12] = {3,42,33,21,145,12,345,12,3,2,3,41};
   int elem3[12] = {3,42,33,21,145,12,345,12,3,2,3,41};


   qsort1(elem1, 0, 11);
   qsort2(elem2, 0, 11);
   mergesort(elem3, 0, 11);

   print(elem1, 12);
   print(elem2, 12);
   print(elem3, 12);
   return 0;
}
两个快速排序的写法和一个归并排序的写法。

你可能感兴趣的:(排序练习--快排 && 归并)