Skip to content
Snippets Groups Projects
Select Git revision
  • dd19d5b290d6dfd86b6087d45d7bcb72ff57417a
  • main default protected
  • latest
3 results

push.bash

Blame
  • sort-5.c 1.08 KiB
    #include <stdio.h>
    #include <string.h>
    #include <unistd.h>
    
    int comparisons = 0;
    
    void display (char **name, int left, int right)
    {
      printf ("\e[H\e[J");
      for (int i = 0; name[i]; i++)
        {
          printf ("%s", name[i]);
          if (i == left || i == right)
            printf (" <--");
          printf ("\n");
        }
      printf ("%d\n", comparisons);
    }
    
    int compare (char **name, int left, int right)
    {
      int result = strcmp (name[left], name[right]);
      comparisons++;
      display (name, left, right);
      usleep (200);
      return result;
    }
    
    int find_first (char **name, int i0)
    {
      int first = i0;
      for (int i = i0 + 1; name[i]; i++)
        if (compare (name, i, first) < 0)
          first = i;
      return first;
    }
    
    void sort (char **name)
    {
      int sorted = 0;
      while (name[sorted])
        {
          int first = find_first (name, sorted);
          char *temp = name[sorted];
          name[sorted] = name[first];
          name[first] = temp;
          sorted++;
        }
    }
    
    int main (void)
    {
      char *name[] = {
                       #include "names.h"
                       NULL
                     };
      sort (name);
      display (name, -1, -1);
      return 0;
    }