C/Data Structure Algorithm/Shaker Sort

Материал из C\C++ эксперт
Перейти к: навигация, поиск

The Shaker Sort

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void shaker(char *items, int count);
int main(void)
{
  char s[255];
  printf("Enter a string:");
  gets(s);
  shaker(s, strlen(s));
  printf("The sorted string is: %s.\n", s);
  return 0;
}

void shaker(char *items, int count) {
  register int i;
  int exchange;
  char t;
  do {
    exchange = 0;
    for(i = count - 1; i > 0; --i) {
      if(items[i - 1] > items[ i ]) {
        t = items[i - 1];
        items[i - 1] = items[ i ];
        items[ i ] = t;
        exchange = 1;
      }
    }
    for(i = 1; i < count; ++i) {
      if(items[i - 1] > items[ i ]) {
        t = items[i-1];
        items[i - 1] = items[ i ];
        items[ i ] = t;
        exchange = 1;
      }
    }
  } while(exchange); /* sort until no exchanges */
}