i trying obtain 2 cluster strings via bubble sort algorithm. main logic putting character strings left side , numbers right side, , positions can not changed according right left reading, need use bubble sort implementation(!)
for example;
if string '503692ec12fatma' need put firstly 'ecfatma50369212' thing didn't how can use bubble sort implement mechanism besides single if statement ?
i tried somethings sort character array via bubble sort can not store old positions, need use 1 array , needs implementation of c.
my code example :
#include<stdio.h> #include<conio.h> #include<string.h> void main() { char st[25],temp; int l,i,j; // clrscr(); printf("enter sting\n"); gets(st); l=strlen(st); /*logic bubble sort */ for(i=1;i<l;i++) for(j=0;j<l-i;j++) if(st[j]>st[j+1]) { temp=st[j]; st[j]=st[j+1]; st[j+1] =temp; } printf("sorted string \n"); printf("%s",st); getch(); }
but gives me : '01223569aacefmt' (!)
after made string 'ecfatma50369212', use string arrange cluster left right < b , 0 < 1.
to : 'aacefmt01223569'
like 2 functions, first function, use bubble sort divide numbers , characters, use functions returned array compare right left sorting create sorted character array.
any appreciated.
to in single pass requires differentiation of digits , non-digits. once have that, algorithm can summed as:
- always swap if have digit in first slot , non-digit in second.
- else, swap if both digits or both non-digits , then, if they're out of order (the higher slot "less than" lower slot).
following that, can in single bubble-run. proper comparison:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> int main() { char st[25] = "503692ec12fatma", temp; size_t len, i; int swapped = 1; puts(st); len = strlen(st); while (swapped && len--) { swapped = 0; (i=0; i<len; ++i) { int swap = !isdigit((unsigned char)st[i+1]); if (isdigit((unsigned char)st[i])) swap = swap || (st[i+1] < st[i]); else swap = swap && (st[i+1] < st[i]); if (swap) { temp = st[i]; st[i] = st[i+1]; st[i+1] = temp; swapped = 1; } } } puts(st); }
output
503692ec12fatma aacefmt01223569
there other ways obviously. can combine madness single if
expression if you're masochist, (i didn't clarity). accomplish both clustering , cluster-sorting, 1 way achieve it.