Skip to content

Instantly share code, notes, and snippets.

@tjhv
Last active February 17, 2018 05:10
Show Gist options
  • Save tjhv/5ac7067ad280131835e12ee80f68f6ff to your computer and use it in GitHub Desktop.
Save tjhv/5ac7067ad280131835e12ee80f68f6ff to your computer and use it in GitHub Desktop.
Example of sorting by ASCII char code
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#define ASIZE 50
char arr[(ASIZE + 1)];
bool k_cmp_chr(char c1, char c2)
{
if(c1 > c2) return true;
return false;
}
char * k_sort_string(char *str)
{
bool has_changed = false;
size_t len = strnlen(str, ASIZE);
for(int i = 0; i < len; ++i)
{
char c1 = *(str + i);
char c2 = *(str + (i + 1));
if(c1 == '\0') break;
if(c2 == '\0') c2 = c1;
if(k_cmp_chr(c1, c2))
{
if(!has_changed) has_changed = true;
arr[i] = c2;
arr[i + 1] = c1;
++i;
continue;
}
arr[i] = c1;
}
if(has_changed) return k_sort_string(arr);
return arr;
}
int main(void)
{
char *str_to_sort_desc = "gfedcba";
char *str_to_sort_asce = "abcdefg";
char *ss = "sort this string all kinds of crazy";
printf("sorted string=%s\n", k_sort_string(ss));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment