Quick sort
// QuickSort.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
void QuickSortStart(int* a, int iLen);
void QuickSort(int* a, int startIndex, int endIndex);
void Swap(int* a, int index1, int index2);
void PrintArray(int a[], int iLen);
int _tmain(int argc, _TCHAR* argv[])
{
int arrayToSort[] = {20, 7, 3, 4, 25, 15, 29, 12, 4, 1};
int n = sizeof(arrayToSort)/sizeof(int);
PrintArray(arrayToSort, n);
QuickSortStart(arrayToSort, n);
PrintArray(arrayToSort, n);
return 0;
}
void QuickSortStart(int* a, int iLen)
{
if(a==NULL)
return;
if(iLen<=0)
return;
QuickSort(a,0,iLen-1);
}
void QuickSort(int* a, int startIndex, int endIndex)
{
if(startIndex>=endIndex)
return;
int ipivot = startIndex;
for(int i=startIndex+1;i<=endIndex;i++)
{
if(a[i]<a[startIndex])
{
ipivot++;
if(ipivot<i)
{
Swap(a,ipivot,i);
}
}
}
if(ipivot>startIndex)
{
Swap(a,startIndex, ipivot);
}
QuickSort(a, startIndex, ipivot-1);
QuickSort(a, ipivot+1, endIndex);
}
void Swap(int* a, int index1, int index2)
{
if(index1!=index2&&a!=NULL)
{
int temp = a[index1];
a[index1] = a[index2];
a[index2] = temp;
}
}
void PrintArray(int a[], int iLen)
{
for(int i=0; i< iLen; i++)
{
std::cout<<a[i]<<' ';
}
std::cout<<std::endl;
}