#include<stdio.h>
/*
* Implemented by Arjun Sunel.
*/
// Method to swap two integers by reference.
void Swap(int *first, int *second)
{
int temp = *first;
*first = *second;
*second = temp;
}
// Method to get the partition index of an array.
int Partition(int array[], int startIndex, int endIndex)
{
int endIndexElement = array[endIndex];
int index;
int tempIndex = startIndex;
for(index = startIndex; index <= endIndex - 1; index++)
{
if(array[index] <= endIndexElement)
{
Swap( &array[index], &array[tempIndex]);
tempIndex++;
}
}
Swap( &array[endIndex], &array[tempIndex]);
return tempIndex;
}
// Quicksort method
void QuickSort(int array[], int startIndex, int endIndex)
{
int partitionIndex;
if(startIndex < endIndex)
{
partitionIndex = Partition(array, startIndex, endIndex);
// Now the element at partition index is fixed, we will recursively call the QuickSort method on the left and right subarrays.
QuickSort(array, startIndex, partitionIndex - 1);
QuickSort(array, partitionIndex + 1, endIndex);
}
}
// Entry point of the program
int main()
{
int array[] = {5, -12, 14, 7};
int arraySize = 4;
int index;
printf("Before sorting : \n");
for(index = 0; index <= arraySize - 1; index++)
{
printf("%d ", array[index]);
}
QuickSort(array, 0, arraySize-1);
printf("\nAfter sorting : \n");
for(index = 0; index <= arraySize - 1; index++)
{
printf("%d ", array[index]);
}
printf("\n");
}
Sunday, 14 December 2014
Recursive QuickSort for Array of Integers
Labels:
Sorting
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment