Reputation: 1
As a school assignment we are writing a bubble sort program in c. The code I wrote works. The only thing is that the output returns the input and doesn't return the swapped input. I'm kinda stuck. No matter what I do i either get an error or nothing changes. Does anybody know what is going wrong? Any help would be highly appreciated!!
#include <stdio.h>
#include <string.h>
#define MAXLENGTH 100
void getString(char *str);
void printResult(char *str);
int greaterThan(char ch1, char ch2);
void swap(char *str, int index1, int index2);
int main(void) {
int len; // length of the entered string
char str[MAXLENGTH]; // input should be no longer than MAXLENGTH
getString(str);
len = strlen(str); // get length of the string, from sting.h
int j;
for (j = 0; j < len-j; j++) {
int i;
for (i = 0; i < len-j; i++){
char ch1 = str[i];
char ch2 = str[i+1];
if (greaterThan(ch1, ch2)) {
swap(str, i, i+1); // swap char 1
swap(str, i, i+1); // swap char 2
}
}
}
printResult(str);
return(0);
}
void getString(char *str) {
printf("Enter the string you would like to sort: ");
scanf("%s",str);
}
void printResult(char *str){
printf("Here is the sorted string: ");
printf("%s",str);
}
int greaterThan(char ch1, char ch2){
return (ch1 > ch2);
}
void swap(char *str, int index1, int index2){
char h = str[index1];
str[index1] = str[index2];
str[index2] = h;
}
Upvotes: 0
Views: 190
Reputation: 655
if (greaterThan(ch1, ch2)) {
swap(str, i, i+1); // swap char 1
swap(str, i, i+1); // swap char 2
}
In this code you are swamping twice.
For Example: str = ['a','b','c'] swap(str,1,2)
for first swap the " str " will be ['a','c','b']
and for the second swap " str " will be ['a','b','c']
. That's why your Output is the same as input.
You Just Need To Call swap
function only once.
if (greaterThan(ch1, ch2)) {
swap(str, i, i+1);
}
Upvotes: 0
Reputation: 1946
Here:
if (greaterThan(ch1, ch2)) {
swap(str, i, i+1); // swap char 1
swap(str, i, i+1); // swap char 2
}
you are swapping twice while you should swap only once.
I was bad the below part of my answer's previous version is not bubble short:
Another problem is that you are using elements next to each other and you are not using i and j indexed ones to compare and swap. So you better should have something like this:
if (greaterThan(str[i], str[j]))
swap(str, i, j);
Upvotes: 1
Reputation: 1373
Try this:
getString(str);
len = strlen(str); // get length of the string, from sting.h
int j;
for (j = 0; j < len-j; j++) {
int i;
for (i = 0; i < len-j; i++){
char ch1 = str[i];
char ch2 = str[i+1];
if (greaterThan(ch1, ch2)) {
swap(str, i, i+1); // swap char 1
}
}
}
printResult(str);
return(0);
}
Upvotes: 2