aboutsummaryrefslogblamecommitdiff
path: root/qsort.c
blob: dbf234b886be8f00db1b7ece2a6c403ae0967551 (plain) (tree)












































































                                                                                                               
#include <stdio.h>

void printia(int array[], int len);
void qsort(int array[], int left, int right);
void swap(int array[], int i, int j);

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

  printf("c> 0 1 2 3 4 5 6 7 8 9\n");
  printia(array, sizeof(array)/sizeof(int));
  qsort(array, 0, sizeof(array)/sizeof(int)-1);
  printia(array, sizeof(array)/sizeof(int));

  return 0;
}

void 
printia(int array[], int len)
{
  int i;

  printf("a> ");
  
  for (i = 0; i < len; i++)
    printf("%d ", array[i]);

  printf("\n");
}

void 
qsort(int array[], int left, int right)
{
  int i, last;

  if (left >= right)
    return;

  printf("1> array[%d] <=> array[%d] | %d <=> %d\n", left, (left+right)/2, array[left], array[(left+right)/2]);
  swap(array, left, (left+right)/2);
  printia(array, 10);
  last  = left;

  for (i = left+1; i <= right; i++)
    if (array[i] < array[left]) {
      printf("2> array[%d] <=> array[%d] | %d <=> %d\n", last+1, i, array[last+1], array[i]);
      swap (array, ++last, i);
      printia(array, 10);
    }
  printf("s> |---------<for loope>-+-------|\n");

  printf("3> array[%d] <=> array[%d] | %d <=> %d\n", left, last, array[left], array[last]);
  swap(array, left, last);
  printia(array, 10);

  qsort (array, left, last-1);
  qsort(array, last+1, right);
  printf("s> |------------<END>----+-------|\n");

}

void
swap(int array[], int i, int j)
{
  int temp;

  if (i == j)
    printf("s> |---------<same swap>-+-------|\n");

  temp = array[i];

  array[i] = array[j];
  array[j] = temp;
}