-
sorting array
Hello!
Code:
main() {
char nome[] = "iiooeeuuaa";
int i;
for(i = 0; nome[i] != '\0'; i++) {
int j;
for(j = 0; j < nome[i] != '\0'; j++) {
if(nome[i] < nome[j]){
char aux = nome[i];
nome[i] = nome[j];
nome[j] = aux;
}
}
}
int j;
for(j = 0; nome[j] != '\0'; j++){
printf("%c", nome[j]);
}
printf("\n");
}
My program objective is to sort a string.
the output must be: aeiou
but this is what happens: aaeeiioouu
thanks
-
You've reached your objective. The reason it's doubling every letter is because your string has 2 of each letter in it. Are you saying that your objective is also to eliminate duplicates or...?
-
my objective is to sort the string, but the letters can't be duplicated
eeiiuuooaa is an example
programming -> agimnopr
-
-
>my objective is to sort the string, but the letters can't be duplicated
The simplest solution is to sort the string, then remove adjacent duplicates:
Code:
#include <stdio.h>
#include <string.h>
void sort(char str[])
{
int i, j;
char save;
if (str[0] == '\0')
return;
for (i = 1; str[i] != '\0'; i++) {
save = str[i];
for (j = i; j >= 1 && save < str[j - 1]; j--)
str[j] = str[j - 1];
str[j] = save;
}
}
void unique(char str[])
{
int i, j;
for (i = 0; str[i] != '\0';) {
if (str[i] == str[i + 1]) {
for (j = i + 1; str[j] != '\0'; j++)
str[j] = str[j + 1];
}
else
++i;
}
}
int main(void)
{
char str[] = "programming";
sort(str);
unique(str);
puts(str);
return 0;
}
Notice that I used an insertion sort instead of the bubble sort. It's shorter, easier to understand, and far more efficient in all but the most exceptional circumstances. Here's some homework for you:
- Why does the sort function terminate if the first element is a null character?
- What purpose does the save variable serve in my sort function?
- Why is the increment section of the outer loop in unique empty?
- Do either of these functions access indices outside of the string's boundaries?
- Make sure that this pair of functions actually works for any input. Consider long strings of duplicates, duplicates at the front and back of the string, and a string with nothing but duplicates.
With that out of the way, can you think of any other ways to solve the problem? What I showed you is not the best solution by any stretch of the imagination.
-
Hlo al. i ned a prgm 2 do this
- Why does the sort function terminate if the first element is a null character?
- What purpose does the save variable serve in my sort function?
- Why is the increment section of the outer loop in unique empty?
- Do either of these functions access indices outside of the string's boundaries?
- Make sure that this pair of functions actually works for any input. Consider long strings of duplicates, duplicates at the front and back of the string, and a string with nothing but duplicates.
With that out of the way, can you think of any other ways to solve the problem?
m n a hry. plz email me the prgm thx
Quzah.