I think you Should to Make a two function. If you select ascending.
like this.
int Ascending(void * a, void * b)
{
int inter_a = *((int*)(a)); int inter_b = *((int*)(b));
if(inter_a > inter_b)
return -1;
else
return 1;
}
int Descending(void * a, void * b)
{
int inter_a = *((int*)(a)); int inter_b = *((int*)(b));
if(inter_a < inter_b)
return -1;
else
return 1;
}
user can Select In Main Function. use Ascending, or Descending. And You call function what user select function.
if(choice == 1)
{
Sort((void*)num, Ascending, sizeof(int), max);
}
else
{
Sort((void*)num, Descending, sizeof(int), max);
}
And CompStr. I think you shold to use string.h.
CompStr has Problem. if a[i] == 'a', b[i] == 'D'. CompStr is think a[i] is comp first. you should to use like this.
int CompStr(void *x, void *y)
{
char *a = (char*)x;
char *b = (char*)y;
int c1 = 0, c2 = 0, cmp = 0, i = 0;
while(a[c1] != '\0') c1 += 1;
while(b[c2] != '\0') c2 += 1;
while((i < c1) && (i < c2))
{
char compA = tolower(a[i]);
char compB = tolower(b[i]);
if(compA == compB)
{
i++;
continue;
}
if(compA < compB)
{
cmp = (-1);
break;
}
if(compA > compB)
{
cmp = 1;
break;
}
}
return cmp;
}
and Test Code =
int main()
{
//first exmaple.
char * str1 = "Hallo.";
char * str2 = "Hello.";
//second exmaple.
char * str3 = "What Does Fox Say?";
char * str4 = "IDOLM@STER";
//third example.
char * str5 = "Stack Overflow.";
char * str6 = "Stack Overflow.";
int result = CompStr((void *)str1, (void *)str2);
int result1 = CompStr((void *)str3, (void *)str4);
int result2 = CompStr((void*)str5, (void*)str6);
printf("1 : %d\n", result);
printf("2 : %d\n", result1);
printf("3 : %d", result2);
return 0;
}
output is 1 : -1 2: 1 3: 0
Code is work well.
this code has problem.
case 4:
{
printf("How many Strings you want to sort ? ");
scanf("%d", &max);
printf("Enter the strings\n");
for (i = 0; i < max; i++) scanf(" %s", str[i]);
Sort((void*)str, CompStr, sizeof(char), max);
printf("Sorted elements are are - \n");
for (i = 0; i < max; i++) printf(" %s\n", str[i]);
break;
}
you want compare string. but sizeof element is just 1 byte. and youre code can
t compile.
void *mem_copy(void *dest, const void *src, unsigned int n)
{
int i;
char* newsrc = (char*)src;
char* newdest = (char*)dest;
for (i = 0; i < n; i++)
newdest[i] = newsrc[i];
}
i use compile VS 2017, you write return type is void *, but function is dosen`t return. is right code? please modified code compile well.