Advertisement
cd62131

Swap and Sort

Feb 5th, 2014
526
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.92 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <ctype.h>
  5. void swap(char *string) {
  6.   for (int i = 0; string[i]; i++) {
  7.     char c = string[i];
  8.     if (islower(c)) string[i] = toupper(c);
  9.     else if (isupper(c)) string[i] = tolower(c);
  10.   }
  11. }
  12. void sort(char *string, int left, int right) {
  13.   if (left >= right) return;
  14.   int i = left, j = right;
  15.   char tmp, pivot = string[rand() % (j - i) + i];
  16.   while (1) {
  17.     while (string[i] < pivot)
  18.       i++;
  19.     while (string[j] > pivot)
  20.       j--;
  21.     if (i >= j) break;
  22.     tmp = string[i];
  23.     string[i] = string[j];
  24.     string[j] = tmp;
  25.     i++;
  26.     j--;
  27.   }
  28.   sort(string, left, i - 1);
  29.   sort(string, j + 1, right);
  30. }
  31. int main(void) {
  32.   char string[] = "cbaZYXcbaZYX";
  33.   printf("Original: %s\n", string);
  34.   swap(string);
  35.   printf("Swap: %s\n", string);
  36.   sort(string, 0, strlen(string) - 1);
  37.   printf("Sort: %s\n", string);
  38.   return 0;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement