Quicksort.c

From Algorithmist
Jump to navigation Jump to search

This is an implementation of Quicksort in C. This algorithm is recursive. Algorithm is a modified version available here [1].

/* C, hand-coded quicksort */
#include <stdio.h>
#include <stdlib.h>

typedef TYPE T;

void quicksort(T* data, int N)
{
  int i, j;
  T v, t;

  if( N <= 1 )
    return;

  // Partition elements
  v = data[0];
  i = 0;
  j = N;
  for(;;)
  {
    while(data[++i] < v && i < N) { }
    while(data[--j] > v) { }
    if( i >= j )
      break;
    t = data[i];
    data[i] = data[j];
    data[j] = t;
  }
  t = data[i-1];
  data[i-1] = data[0];
  data[0] = t;
  quicksort(data, i-1);
  quicksort(data+i, N-i);
}