7

Problem

I have made sorting program which is similiar to other found at

https://beginnersbook.com/2015/02/c-program-to-sort-set-of-strings-in-alphabetical-order/

but program which i made is not working. I think both are same but my program giving me waste output.

Also i want to know in other program count is set to 5 for example and it should take 6 input starting from 0 but it is getting only 5,How?

My Program

#include <string.h>
#include <stdio.h>

int main() {

char str[4][10],temp[10];
int i,j;
printf("Enter strings one by one : \n");
for(i=0;i<5;i++)
    scanf("%s",str[i]);

for(i=0;i<5;i++)
    for(j=i+1;j<5;j++)
        if(strcmp(str[i],str[j])>0){
            strcpy(temp,str[i]);
            strcpy(str[i],str[j]);
            strcpy(str[j],temp);
        }

printf("\nSorted List : ");
for(i=0;i<5;i++)
    printf("\n%s",str[i]);
printf("\n\n");

return 0;

}
5
  • 1
    You're storing six strings in an array with only enough room for four, and with no checks on the length of these strings (which have to be 9 characters or less). No wonder it doesn't work. Commented Dec 24, 2017 at 9:34
  • You have a 4-element array, and you are trying to put 6 elements in it. Try with 'char str[6][10],temp[10];' for better experience. Commented Dec 24, 2017 at 9:35
  • 4 element ? i think array starts from 0 so it should be 5 element array(re-edited to store 5) Commented Dec 24, 2017 at 9:39
  • 1
    You think that wrong: a [4] array has 4 elements, valid indices are 0, 1, 2 and 3. See my previous suggestion. Your algorithm may work, but it ruins the variables, and presumably crashes afterwards. This is exactly why C is considered 'dangerous'. Commented Dec 24, 2017 at 9:41
  • Thank you,tevemadar.Now i just want to know how other program is storing only 5 elements on input 5 as count bcoz starting from 0 to 5 means to execute loop 6 times but loop executing only 5 times for input. Commented Dec 24, 2017 at 9:47

6 Answers 6

17

Use qsort().

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int pstrcmp( const void* a, const void* b )
{
  return strcmp( *(const char**)a, *(const char**)b );
}

int main()
{
  const char* xs[] =
  {
    "Korra",
    "Zhu Li",
    "Asami",
    "Mako",
    "Bolin",
    "Tenzin",
    "Varrick",
  };
  const size_t N = sizeof(xs) / sizeof(xs[0]);

  puts( "(unsorted)" );
  for (int n = 0; n < N; n++)
    puts( xs[ n ] );

  // Do the thing!
  qsort( xs, N, sizeof(xs[0]), pstrcmp );

  puts( "\n(sorted)" );
  for (int n = 0; n < N; n++)
    puts( xs[ n ] );
}

Please don’t use bubble sort. In C, you really do not have to write your own sorting algorithm outside of specialized needs.

Sign up to request clarification or add additional context in comments.

2 Comments

Give us the output.
The output is not going to be surprising in any way whatsoever.
2

Here is a program which will sort and print your inputted strings. Answering a little late, but just in case others have a similar question.

// This program will sort strings into either ascending or descending order
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_SIZE            1000
#define EQUAL               0
#define ASCENDING           0
#define DESCENDING          1

// Function prototypes
void swap_str(char str1[], char str2[]);
void sort_strings(char str[MAX_SIZE][MAX_SIZE], int len, int order_type);
void print_2d_array(char str[MAX_SIZE][MAX_SIZE], int len);

int main(void) {

    int order_type;
    char str[MAX_SIZE][MAX_SIZE];

    // User selecting the order type
    printf("-----------[Order Type]-----------\n");
    printf("Sort your strings in ascending or descending order?\n");
    printf("0 = Ascending | 1 = descending\n");

    scanf("%d", &order_type);
    if (order_type != ASCENDING && order_type != DESCENDING) {
        printf("Please enter 0 or 1\n");
        exit(1);
    }

    // User inputting their strings
    printf("---------[Enter Strings]----------\n");
    printf("Enter Strings one by one.\n");
    printf("Max Strings: %d | Max String Len: %d\n", MAX_SIZE, MAX_SIZE);

    int i = 0;
    while ((i < MAX_SIZE) && (scanf("%s", str[i]) == 1)) i++;
    if (i == MAX_SIZE) printf("You reached the maximum strings allowed\n"); 

    // Program output of the sorted strings    
    printf("---------[Sorted Strings]---------\n");
    sort_strings(str, i, ASCENDING);
    print_2d_array(str, i);

    return 0;
}

// Swaps two strings (assuming memory allocation is already correct)
void swap_str(char str1[], char str2[]) {

    char temp[MAX_SIZE];

    strcpy(temp, str1);
    strcpy(str1, str2);
    strcpy(str2, temp);

}

// Will sort a 2D array in either descending or ascending order,
// depending on the flag you give it
void sort_strings(char str[MAX_SIZE][MAX_SIZE], int len, int order_type) {

    int i = 0;
    while (i < len) {

        int j = 0;
        while (j < len) {

            if ((order_type == ASCENDING) &&
                (strcmp(str[i], str[j]) < EQUAL)) {

                swap_str(str[i], str[j]);
            } else if ((order_type == DESCENDING) &&
                (strcmp(str[i], str[j]) > EQUAL)) {

                swap_str(str[i], str[j]);
            }

            j++;
        }

        i++;
    }

}

// Will print out all the strings 2d array
void print_2d_array(char str[MAX_SIZE][MAX_SIZE], int len) {

    int i = 0;
    while (i < len) {
        printf("%s\n", str[i]);
        i++;
    }
}

Example (Ascending order):

-----------[Order Type]-----------
Sort your strings in ascending or descending order?
0 = Ascending | 1 = descending
0
---------[Enter Strings]----------
Enter Strings one by one.
Max Strings: 1000 | Max String Len: 1000
Mango
Watermelon
Apple
Banana
Orange
// I pressed CTRL+D here (Linux) or CTRL+Z then enter (on Windows). Essentially triggering EOF. If you typed the MAX_SIZE it would automatically stop.
---------[Sorted Strings]---------
Apple
Banana
Mango
Orange
Watermelon

1 Comment

Please use the site as a general CS QA site, not a homework solving site. Don't provide direct solutions. Guide them where they are not correct.
1

it should take 6 input starting from 0 but it is getting only 5,How?

This loop

for(i=0;i<5;i++)
    scanf("%s",str[i]);

execute for i being 0, 1, 2, 3, 4 so it loops 5 times.

If you want 6 loops do

for(i=0;i<=5;i++)
          ^
          Notice

or

for(i=0;i<6;i++)
          ^
          Notice

Also notice this line

char str[6][10],temp[10];
         ^
         Notice

so that you reserve memory for 6 strings

2 Comments

Not in my program but the program found at beginnersbook.com/2015/02/… is taking only 5 input when for(i=0;i<=count;i++) is used and 5 is entered for count
I think it is because of gets but what is gets doing to take only 5
0

This is not an answer, but some criticism of the code you refer to:

#include<stdio.h>
#include<string.h>
int main(){
  int i,j,count;
  char str[25][25],temp[25];
  puts("How many strings u are going to enter?: ");
  scanf("%d",&count);                                        // (1)

  puts("Enter Strings one by one: ");
  for(i=0;i<=count;i++)                                      // (2)
    gets(str[i]);
  for(i=0;i<=count;i++)
    for(j=i+1;j<=count;j++){
      if(strcmp(str[i],str[j])>0){
        strcpy(temp,str[i]);
        strcpy(str[i],str[j]);
        strcpy(str[j],temp);
     }
  }
  printf("Order of Sorted Strings:");                        // (3)
  for(i=0;i<=count;i++)
    puts(str[i]);

  return 0;
}

And the criticism:

(1) scanf("%d",&count); reads a number into count, and returns after that. It does not consume the line break(!)

(2) this loop does not print anything, just reads. However if you put

  for(i=0;i<=count;i++){
    printf("%d:",i);
    gets(str[i]);
  }

in its place, you will suddenly see that it asks for names 0...5, just skips the 0 automatically. That is where the line break is consumed, it reads an empty string. You can also make it appear, if instead of putting 5 into the initial question, you put 5 anmoloo7.

(3) in the printout the names appear below the title Order of Sorted Strings. But there is no linebreak in that printf. The thing is that the empty string is "smaller" than any other string, so it gets to the front of the list, and that is printed there first. If you do the 'trick' of appending a name after the initial number, the output will look different, there will be 6 names, and one of them appended directly to the title.

Plus there is the thing what you probably get from your compiler too: gets is a deadly function, forget its existence and use fgets with stdin as appears in other answers.

Comments

0

I have this sample that I made:

#include <stdio.h>
#include <string.h>
void main()
{
  char str[100],ch;
  int i,j,l;

       printf("\n\nSort a string array in ascending order :\n");
       printf("--------------------------------------------\n");  
       printf("Input the string : ");
       fgets(str, sizeof str, stdin);
  l=strlen(str);
  /* sorting process */
  for(i=1;i<l;i++)
    for(j=0;j<l-i;j++)
    if(str[j]>str[j+1])
    {
      ch=str[j];
      str[j] = str[j+1];
      str[j+1]=ch;
    }
   printf("After sorting the string appears like : \n");
   printf("%s\n\n",str);
  }

1 Comment

This code will sort array of characters (one string), but the question is to sort array of strings.
0
#include <stdio.h>
#include <string.h>

#define STRING_MAX_WIDTH 255

void sort_strings(char str_arr[][STRING_MAX_WIDTH],int len){
    char temp[STRING_MAX_WIDTH];
    for(int i=0;i<len-1;i++){
        if(strcmp(&str_arr[i][0],&str_arr[i+1][0])>0){
            strcpy(temp, str_arr[i+1]);
            strcpy(str_arr[i+1],str_arr[i]);
            strcpy(str_arr[i],temp);
            sort_strings(str_arr, len);
        }
    
    }
}

int main(){
   char str_arr[][STRING_MAX_WIDTH] = {"Test", "Fine", "Verb", "Ven", "Zoo Keeper", "Annie"};
   int len = sizeof(str_arr)/STRING_MAX_WIDTH;
   sort_strings(str_arr, len);
   for(int i=0;i<len;i++){
        printf("%s\r\n", str_arr[i]);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.