Saturday, July 22, 2017

quicksort!!!

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

int arrLength(list_t* list)
{
  if(list->head == NULL) return 0;

  element_t* el = list->head;
  int num = 1;
  while(el->next != NULL){
    num++;
    el = el->next;
  }
  return num;
}

void swap(list_t* list, int i, int j)
{
  int x;
  x = list_index(list, i)->val;
  list_index(list, i)->val = list_index(list, j)->val;
  list_index(list, j)->val = x;
}

int partition(list_t* list, int low, int high)
{
  int pivot = list_index(list, low)->val;
  int i = low; int j = high;
  while(1){
    while(i<high){
      if(list_index(list, i)->val <= pivot){
        i++;
      }
    }
    do j--; while(list_index(list, j)->val > pivot);
    if( i>=j )break;
    swap(list, i, j);
  }
  swap(list, low, j);
  return j;
}

void quicksort(list_t* list, int low, int high)
{
  if(low<high){
    int pivot = partition(list, low, high);
    quicksort(list, low, pivot-1);
    quicksort(list, pivot+1, high);
  }
}

void list_sort(list_t* list)
{
  int n = arrLength(list)-1;
  quicksort(list, 0, n);
}

int main()
{
  list_t* list = list_create();

  list_append(list, 3);
  list_append(list, 2);
  list_append(list, 8);
  list_append(list, 5);
  list_append(list, 7);

  list_sort(list);

  return 0;
}

No comments:

Post a Comment