#include <stdio.h> #include <string.h> #define MAX_LEN 20 #define WORD_COUNT 6 char set[][WORD_COUNT] = {"appl","paal","aplep","bb","leapp","hello"};
char* sign(char *result) { int j = 0; int i = 1; char tmp = ' '; while (result[i] != '\0') { tmp = result[i]; for(j = i; j > 0 && result[j-1] > tmp; j--) { result[j] = result[j-1]; } result[j] = tmp; i++; } return result; }
int compare_by_sign(char *a, char *b) { char sort_a[MAX_LEN]; char sort_b[MAX_LEN]; strcpy(sort_a, a); strcpy(sort_b, b);
return strcmp(sign(sort_a), sign(sort_b)); }
int compare(char *a, char *b) { return strcmp(a, b); }
void swap(int i, int j){ if (i == j) return; char tmp[MAX_LEN]; strcpy(tmp, set[i]); strcpy(set[i], set[j]); strcpy(set[j], tmp); }
void qsort(int l, int u) { if (l > u) return; int m = l;
for(int i = l+1; i <= u; i++) { if(compare_by_sign(set[i], set[l]) < 0){ swap(i,++m); } } swap(m,l);
qsort(l, m-1); qsort(m+1, u); }
void bsearch(int l, int u, char *word_sign, int *is_found) { int mid = (u - l) / 2; if (l > u) { return; } char mid_sign[MAX_LEN]; strcpy(mid_sign, set[mid]); sign(mid_sign); int com_result = compare(mid_sign, word_sign); if (com_result > 0) bsearch(l, mid-1, word_sign, is_found); if (com_result < 0) bsearch(mid+1, u, word_sign, is_found); if (com_result == 0){ int flag = mid; printf("found brother word:\n%s\n",set[mid]); *is_found = 1; mid--; flag++; while(mid > 0){ if(compare(sign(set[mid]), word_sign) == 0) printf("%s\n",set[mid]); else break; mid--; } while(flag < WORD_COUNT) { if(compare(sign(set[flag]), word_sign) == 0) printf("%s\n",set[flag]); else break; flag++; } } }
int main() { qsort(0, WORD_COUNT-1); char des[] = "apple"; char *word_sign; word_sign = sign(des); printf("sign is: %s\n", word_sign);
int is_found = 0; bsearch(0, WORD_COUNT, sign(des), &is_found); if (is_found == 0) { printf("%s\n", "can not found brother word!!"); } }
|