Skip to lab content

UNIT 05 · Sorting and Searching

Sort an array of names

EXERCISE 05FC173 sample runs

THE SYLLABUS QUESTION

What you need to solve

Write a C program that sorts a given array of names.
Input format & conventions

Line 1: number of names (1–20). Next n lines: non-empty names, each at most 63 bytes. Spaces within names are allowed. Sorting is ascending, case-sensitive lexicographic order using strcmp; examples use ASCII.

UNDERSTAND THE IDEA

Explanation

Store names in a two-dimensional character array. Each row is one null-terminated string.

strcmp compares string contents. If the left name is greater, swap the entire strings using a temporary buffer and strcpy. This example uses bubble sort.

The order is byte-based and case-sensitive, rather than locale-aware dictionary order. Use a consistent letter case if that is the desired classroom ordering.

PLAN BEFORE CODING

Algorithm

  1. Read the count and consume the rest of its input line.
  2. Read each bounded name, preserving embedded spaces.
  3. Compare adjacent names with strcmp.
  4. Swap complete strings when they are out of order.
  5. Print the sorted names, one per line.

SEE THE CONTROL FLOW

Flowchart

Follow the arrows from Start. Diamonds ask a question; labeled arrows show the answer. A returning arrow repeats a loop. Function internals are grouped where needed; later input checks follow the rules in the program.

Flowchart for Sort an array of names: input, decisions, processing, output and loop paths

On a phone, scroll sideways to read the diagram at full size. Open full-size flowchart ↗

C17

Complete C program

Download .c
#include <stdio.h>
#include <string.h>
#define MAX_NAMES 20
#define NAME_SIZE 64

int readLine(char text[], size_t capacity) {
    if (fgets(text, (int)capacity, stdin) == NULL) return 0;
    size_t length = strlen(text);
    if (length > 0 && text[length - 1] == '\n') text[--length] = '\0';
    else if (!feof(stdin)) {
        int ch = getchar();
        if (ch != '\n' && ch != EOF) return 0;
    }
    if (length > 0 && text[length - 1] == '\r') text[length - 1] = '\0';
    return 1;
}

int main(void) {
    char names[MAX_NAMES][NAME_SIZE], temporary[NAME_SIZE];
    int n, ch;
    if (scanf("%d", &n) != 1 || n < 1 || n > MAX_NAMES) {
        puts("Invalid input."); return 1;
    }
    while ((ch = getchar()) != '\n' && ch != EOF) { }
    for (int i = 0; i < n; ++i) {
        if (!readLine(names[i], sizeof names[i]) || names[i][0] == '\0') {
            puts("Invalid input."); return 1;
        }
    }
    for (int pass = 0; pass < n - 1; ++pass)
        for (int j = 0; j < n - 1 - pass; ++j)
            if (strcmp(names[j], names[j + 1]) > 0) {
                strcpy(temporary, names[j]);
                strcpy(names[j], names[j + 1]);
                strcpy(names[j + 1], temporary);
            }
    puts("Sorted names:");
    for (int i = 0; i < n; ++i) puts(names[i]);
    return 0;
}
Open in compiler ↗

Code loads into the existing compiler. Enter the sample input there; sign-in and execution rules stay the same.

Compile and run locally
gcc -std=c17 sort-names.c -o lab
./lab

On Windows, run .\lab.exe after compiling with GCC. The interest program requires the math library where applicable.

FOLLOW THE VALUES

Dry run

Step / stateOperationResult
Names: Venu, Anu, BhavyaCompare Venu and AnuSwap
Compare Venu and BhavyaSwapAnu, Bhavya, Venu
Next passAnu precedes BhavyaSorted

CHECK THE BEHAVIOR

Sample input & output

Each output below was produced by compiling and running this exact program. Input values are entered in the stated order; the examples do not print input prompts.

Sample 1

INPUT
3
Venu
Anu
Bhavya
OUTPUT
Sorted names:
Anu
Bhavya
Venu

Sample 2

INPUT
3
Mary Jane
Anu
Zoya
OUTPUT
Sorted names:
Anu
Mary Jane
Zoya

Sample 3

INPUT
1
Ravi
OUTPUT
Sorted names:
Ravi

Common mistakes

  • Use strcmp instead of comparing string pointers with >.
  • Use a temporary string buffer large enough for the whole name.

WHY THIS GROWTH RATE?

Time and space complexity

Time O(n² × L), where L is the maximum name length; O(L) additional swap storage.

Let n be the number of names and L the maximum name length. The nested bubble-sort loops make n(n − 1)/2 comparisons. strcmp may examine up to L characters per comparison, and each swap copies strings with O(L) work.

Combining O(n²) pair operations with O(L) string work gives O(n² × L) worst-case time. This version has no early-stop flag, so even sorted names still undergo all pair comparisons; comparisons may be faster when names differ near the beginning.

The names array uses O(n × L) input storage. The temporary name buffer used for a swap requires O(L) extra storage. Here the buffers are capped at 20 names of 63 characters, but the formula explains how the algorithm scales with these quantities.

Big-O describes how work grows as the stated input quantity grows; fixed factors and lower-order terms are omitted. The analysis treats fixed-width arithmetic as constant cost and the published limits as practical safety bounds.