> For the complete documentation index, see [llms.txt](https://42-guide.gitbook.io/42-guide/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://42-guide.gitbook.io/42-guide/piscine-life/c06/ft_sort_params.md).

# ft\_sort\_params

**Objective:**

Create a program that displays its given arguments sorted in ASCII order, one per line (excluding the program name itself, `argv`).

**Turn-in Directory:**

`ex03/`

**Files to Turn In:**

`ft_sort_params.c`

**Allowed Functions:**

`write`

**Prototype:**

```c
int main(int argc, char **argv);
```

**Detailed Explanation:**

This program takes command-line arguments, sorts them alphabetically (ASCII order), and prints each sorted argument on a separate line. It excludes the program name (`argv`) from the sorting and printing process. The program implements a sorting algorithm (likely a simple one like bubble sort) and a string comparison function.

**Code Implementation:**

```c
#include <unistd.h>

// Function to print a string followed by a newline
void	ft_putstr(char *str)
{
    // Iterate through the string until the null terminator is reached
	while (*str)
        // Write one character at a time to standard output
		write(1, str++, 1);
    // Write a newline character to standard output after the string
	write(1, "\n", 1);
}

// Function to swap two strings (pointers)
void	ft_swap(char **s, char **s1)
{
	char	*tmp; // Temporary pointer to hold one of the strings

	tmp = *s;  // Store the value of the first pointer in tmp
	*s = *s1;  // Assign the value of the second pointer to the first
	*s1 = tmp; // Assign the original value of the first pointer (stored in tmp) to the second pointer
}

// Function to compare two strings (similar to strcmp)
int	ft_strcmp(char *str, char *str1)
{
    // Continue comparing characters as long as they are equal and not the end of the string
	while (*str == *str1 && *str)
	{
		str++; // Move to the next character in the first string
		str1++; // Move to the next character in the second string
	}
    // Return the difference between the ASCII values of the first differing characters
	return (*str - *str1);
}

// Function to sort the arguments
void	ft_sort(char **argv, int argc)
{
	int	i; // Loop counter
	int	j; // Loop counter
	int	len; // Length of the argument list

	len = argc; // Store the number of arguments
    // Outer loop to iterate through the argument list
	while (len - 1)
	{
		i = 0; // Reset i for each pass
		j = 1; // Reset j for each pass
        // Inner loop to compare adjacent arguments
		while (j < len)
		{
            // If the first argument is greater than the second, swap them
			if (ft_strcmp(argv[i], argv[j]) > 0)
				ft_swap(&argv[i], &argv[j]); // Swap the strings if they are in the wrong order
			i++; // Increment i to move to the next argument
			j++; // Increment j to move to the next argument
		}
		len--; // Decrement len to reduce the number of passes needed
	}
}

int	main(int argc, char *argv[])
{
	if (argc <= 1) // If there are no arguments (other than the program name), exit
		return (0);
	ft_sort(argv + 1, argc - 1); // Sort the arguments (excluding the program name)
    // Iterate through the sorted arguments and print them
	while (*(++argv))
		ft_putstr(*argv); // Print each argument
    return (0);
}
```

**Example Usage:**

If the compiled executable is named `a.out`, running it with arguments would produce the following output:

```c
$> ./a.out zebra apple banana | cat -e
apple$
banana$
zebra$
$>
```

**Edge Cases to Consider:**

* **No arguments**: If only the program name is provided (e.g., `./a.out`), nothing should be printed.
* **Multiple arguments**: The program should correctly sort and print all arguments, regardless of the number.
* **Arguments with mixed case**: Sorting should be based on ASCII values, so uppercase letters will come before lowercase letters.
* **Arguments with special characters**: The program should handle arguments containing special characters according to their ASCII values.

**How It Works:**

1. **Include Header:** The `unistd.h` header is included for the `write` function.
2. **`ft_putstr` Function:**
   * This helper function takes a string (`char *str`) as input.
   * It iterates through the string character by character using a `while` loop until it reaches the null terminator (`\0`).
   * Inside the loop, it calls the `write` function to print one character at a time to the standard output.
   * After printing the entire string, it prints a newline character () to move the cursor to the next line.
3. **`ft_swap` Function:**
   * This function takes two pointers to strings (`char **s`, `char **s1`) as input.
   * It swaps the pointers, effectively swapping the strings they point to.
   * A temporary pointer `tmp` is used to facilitate the swapping process.
4. **`ft_strcmp` Function:**
   * This function takes two strings (`char *str`, `char *str1`) as input.
   * It compares the strings character by character until it finds a difference or reaches the end of one of the strings.
   * It returns the difference between the ASCII values of the first differing characters. This difference is negative if `str` comes before `str1`, positive if `str` comes after `str1`, and zero if the strings are equal.
5. **`ft_sort` Function:**
   * This function takes an array of strings (`char **argv`) and the number of strings in the array (`int argc`) as input.
   * It sorts the array of strings using a bubble sort algorithm.
   * The outer loop iterates through the array `argc - 1` times
   * The inner loop compares adjacent strings using `ft_strcmp`.
   * If two strings are in the wrong order, it swaps them using `ft_swap`.
6. **Main Function:**
   * The `main` function takes `argc` (argument count) and `argv` (argument vector) as parameters.
   * It checks if there are any arguments other than the program name (`if (argc <= 1)`). If not, it exits.
   * It calls the `ft_sort` function to sort the arguments (excluding the program name). The pointer `argv + 1` is passed to `ft_sort` to point to the first argument after the program name, and `argc - 1` is passed as the number of arguments to sort.
   * The `while (*(++argv))` loop iterates through the sorted arguments. The `++argv` increments the pointer to the next argument *before* dereferencing it. This means that in the first iteration, `argv` will be `argv + 1` (skipping the program name).
   * Inside the loop, `ft_putstr(*argv)` is called to print the current argument string followed by a newline character.
   * The program returns 0 to indicate successful execution.

**Key Points to Remember:**

* Implement a sorting algorithm to arrange the arguments in ASCII order.
* Use a string comparison function (like `ft_strcmp`) to compare arguments.
* Remember to exclude the program name from the sorting and printing process.
* Ensure that a newline character is printed after each argument to fulfill the requirement of printing one argument per line.
* Be mindful of pointer arithmetic when passing arguments to the sorting function and when printing the sorted arguments.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://42-guide.gitbook.io/42-guide/piscine-life/c06/ft_sort_params.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
