{"id":50737669,"url":"https://github.com/barrarrr/push_swap","last_synced_at":"2026-06-10T15:02:03.429Z","repository":{"id":337479626,"uuid":"1144217327","full_name":"barraRRR/push_swap","owner":"barraRRR","description":"The goal of push_swap is to sort data on a stack with a limited set of instructions, using the lowest possible number of actions.","archived":false,"fork":false,"pushed_at":"2026-02-19T11:07:49.000Z","size":45917,"stargazers_count":0,"open_issues_count":1,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-04-21T18:37:55.106Z","etag":null,"topics":["42","42school","algorithm","push-swap"],"latest_commit_sha":null,"homepage":"","language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/barraRRR.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-01-28T12:41:25.000Z","updated_at":"2026-02-19T11:07:58.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/barraRRR/push_swap","commit_stats":null,"previous_names":["barrarrr/push_swap"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/barraRRR/push_swap","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/barraRRR%2Fpush_swap","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/barraRRR%2Fpush_swap/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/barraRRR%2Fpush_swap/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/barraRRR%2Fpush_swap/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/barraRRR","download_url":"https://codeload.github.com/barraRRR/push_swap/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/barraRRR%2Fpush_swap/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34157453,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-10T02:00:07.152Z","response_time":89,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["42","42school","algorithm","push-swap"],"created_at":"2026-06-10T15:02:02.688Z","updated_at":"2026-06-10T15:02:03.421Z","avatar_url":"https://github.com/barraRRR.png","language":"C++","funding_links":[],"categories":[],"sub_categories":[],"readme":"_This project has been created as part of the 42 curriculum by edsole-a and jbarreir._\n\n# push_swap\n\nThe goal of push_swap is to sort data on a stack with a limited set of instructions, using the lowest possible number of actions.\n\n## Description\nThis version focuses on algorithmic flexibility, featuring an Adaptive Strategy Selector that chooses the most efficient sorting method based on the input's size and entropy (disorder).\n\n## Instructions\n\n### Compilation\n\nThe project includes a Makefile with all standard 42 rules. To compile the executable, run:\n\n```Bash\nmake\n```\nThis will generate the push_swap binary in the root directory. Other available rules:\n\n- `make clean`: Removes object files.\n- `make fclean`: Removes object files and the push_swap binary.\n- `make re`: Performs a full recompilation.\n\n### Execution\n\nThe program takes a list of integers as arguments. It can handle both individual arguments and quoted strings.\n\n#### Basic Usage:\n\n```Bash\n./push_swap 3 2 1\n./push_swap \"3 2 1\"\n```\n#### With Checker (Verification):\nTo verify the output is correct and count the operations:\n\n```Bash\nARG=\"4 67 3 87 23\"; ./push_swap $ARG | ./checker_linux $ARG\n```\n#### Advanced Modes \u0026 Benchmarking\n\nOur implementation features an Adaptive Mode and a custom Benchmark suite.\n\n#### Strategy Overrides:\nYou can force a specific algorithm using flags:\n\n- `--simple`: Forces Selection Sort.\n- `--medium`: Forces Hourglass Sort.\n- `--complex`: Forces Radix Sort.\n\n#### Performance Metrics:\nEnable the benchmark report (outputs to stderr):\n\n```Bash\n./push_swap --bench 5 2 8 1 9\n```\n\n#### Error Handling:\nThe program strictly validates all input. It will display Error on stderr and exit with a non-zero status if:\n\n- Arguments are not integers.\n- Any integer exceeds INT_MIN or INT_MAX.\n- There are duplicate values in the input.\n\n### Technical Architecture\n\n#### Data Structures\nTo allow efficient manipulation of both the top and the bottom of the stacks (required for rotate and reverse rotate operations), we implemented a Doubly Linked List.\n\n```C\ntypedef struct s_node\n{\n    int             value;\n\tunsigned int    index;\n    struct s_node   *next;\n    struct s_node   *prev;\n} \tt_node;\n```\n\n```c\ntypedef struct s_stack\n{\n\tt_lst           *head;\n\tt_lst           *tail;\n} \tt_stack;\n```\n\n\n#### Strategy Management\nWe use a dedicated structure to store the configuration detected during the parsing phase. This determines the algorithm complexity and enables the diagnostic mode.\n\n```C\ntypedef enum e_complexity\n{\n    DEFAULT,\n    SIMPLE,\n    MEDIUM,\n    COMPLEX,\n    ADAPTIVE\n}\tt_complexity;\n```\n\n```c\ntypedef struct s_strat\n{\n    t_complexity    complex;\n    bool            defined;\n\tint\t\t\t\ttotal;\n\tfloat\t\t\tdisorder;\n}\tt_strat;\n```\n\n### Parsing \u0026 Input Validation\n\nThe parsing logic is designed to be robust, handling multiple input formats seamlessly (separated arguments, quoted strings, or a mix of both).\n\n#### **The Parsing Workflow**\n\n1. **Argument Normalization**\n   - We use a custom `ps_split` to convert the `argv` into a unified array of strings. \n   - This ensures that all the following inputs are treated identically:\n     - **Separate:** `./push_swap 1 2 3`\n     - **Quoted:** `./push_swap \"1 2 3\"`\n     - **Mixed:** `./push_swap \"1 2\" 3` or `./push_swap 1 \"2 3\"`\n\n2. **Flag Detection**\n   - The parser scans for optional selectors to set the sorting strategy:\n     - `--simple`, `--medium`, `--complex`, `--adaptive`\n   - It also identifies the `--bench` flag to enable performance metrics in `stderr`.\n\n3. **Strict Validation**\n   - **Type Check:** Verifies that each argument consists only of valid integers.\n   - **Overflow Check:** Ensures numbers are within the `INT_MIN` and `INT_MAX` range.\n   - **Uniqueness Check:** Scans for duplicate values to prevent invalid stack states.\n\n4. **Stack Population**\n   - Once validated, integers are pushed into **Stack A** (Doubly Linked List).\n   - The order of appearance is strictly maintained: the first number provided becomes the **top** of the stack.\n\n\n```\n\t   [ Start: argv ]\n              |\n              v\n     +------------------+\n     |     ps_split     | \u003c--- Normalizes multiple args and \n     +------------------+      quoted strings into a clean array\n              |\n              v\n    +--------------------+\n    |  Loop through array| \u003c--- Processing each string\n    +--------------------+\n      /       |        \\\n     /        |         \\\n    v         v          v\n+-------+  +-------+  +-----------+\n| FLAGS |  | NUMS  |  |  ERRORS   |\n+-------+  +-------+  +-----------+\n    |         |              |\n    |         |              +------\u003e [ ps_exit ]\n    |         |                       Print \"Error\\n\"\n    |         |                       Free memory\n    |         v                       Exit(1)\n    |    +------------+\n    |    | Validation | \u003c--- 1. Is Numeric?\n    |    +------------+      2. Is Int? (Overflow)\n    |         |              3. Is Duplicate?\n    |         v\n    |    +------------+\n    +--\u003e | t_strategy | \u003c--- Updates: .complexity\n         +------------+           .bench_mode\n              |\n              v\n      +----------------+\n      |  Create Stack  | \u003c--- Pushes validated numbers\n      +----------------+      into Doubly Linked List\n              |\n              v\n       [ Ready to Sort ]\n```\n\n## Algorithmic Rationale \u0026 Complexity\n\nOur sorting architecture is divided into three regimes based on the input size (n) and the Disorder Coefficient (D).\n\n### Heuristic Selection (The Disorder Coefficient)\n\nTo ensure the most efficient approach, the program calculates the `Disorder Coefficient (D)` before performing any operations. This is done by counting inversions (pairs of elements that are in the wrong relative order).\n\n| Regime | Condition | Strategy | Rationale |\n| ------ | --------- | -------- | --------- |\n| Simple | n≤5 or D\u003c0.2 | Selection Sort\t| For small or nearly sorted sets, selecting the minimum is the most direct path to order with minimal logic overhead. |\n| Medium | 2≤D\u003c0.5 | Hourglass Sort | Optimized for average distributions. It uses a sliding window to pre-sort Stack B, outperforming Radix in move count. |\n| Complex | D≥0.5 | Radix Sort | Used when entropy is high. Bitwise partitioning ensures a stable, predictable performance regardless of data chaos. |\n\n### Selection Sort (O(n^2))\n\nOur strategy for small sets or nearly sorted stacks.\n\n- **Path of Least Resistance**: The algorithm repeatedly scans Stack A to find the absolute minimum value. By pushing the smallest elements to Stack B one by one, we effectively \"shorten\" the problem until only 3 elements remain in Stack A.\n\t- If the index is in the upper half, it uses `ra`.\n\t- If the index is in the lower half, it uses `rra`.\n- **Tiny Sort**: Once the stack is reduced to 3 elements, a hardcoded logic solves it in a maximum of `3 moves`, regardless of their initial position.\n- **Move Bound**: For n=5, the upper bound is 12 moves.\n\n### Hourglass Sort (O(n√n))\n\nThis is our primary engine for the 100 and 500 number challenges. It pushes elements to Stack B in a way that resembles an hourglass shape.\n\n- **Newton-Raphson Optimization**: To determine the ideal `\"radius\" (r)` for the sliding window without using forbidden math libraries, we implemented a custom square root function: `r = newton_sqrt(n) × 1.2`. This ensures the window size is mathematically tuned to the input size n.\n- **Sliding Window**: By rotating Stack B based on the `element's index`, we keep the smallest and largest values of each chunk at the extremes, facilitating a much faster recovery to Stack A.\n- **Instruction Coupling**: The algorithm looks ahead to the next node; if both stacks require a rotation, it utilizes `rr` or `rrr` to merge two moves into one.\n- **Move Bound**: For n=100, our implementation stays under 700 moves.\n\n### Radix Sort (O(n log n))\n\nFor stacks with high entropy, Radix Sort provides a consistent bitwise partitioning.\n\n- **Normalization (Indexing)**: We map every value to its rank (0 to n−1). This *\"compression\"* ensures that the algorithm only processes the necessary number of bits (e.g., 9 bits for 500 numbers), regardless of whether the original integers were very large or negative.\n- **Bitwise Partitioning**: It iterates through **each bit**, pushing elements with a 0 bit to Stack B and rotating those with a 1 bit in Stack A, ensuring a stable sort across multiple passes.\n- **Move Bound**: While Radix Sort has a higher move bound than Hourglass **(averaging ~6700 moves for n=500)**, it is used as a fallback for *high-entropy stacks (D≥0.5)* because its performance is **constant** and independent of the initial distribution, ensuring the stack is sorted in a predictable number of operations where heuristic-based windowing might struggle. \n\n## Benchmark \u0026 Diagnostic Mode\nOur implementation features a built-in diagnostic suite designed to analyze algorithmic performance. To maintain compliance with the project's output requirements, the program utilizes I/O Stream Redirection: sorting instructions are sent to the standard output (`stdout`), while performance metrics are directed to the standard error (`stderr`).\n\n### Usage\n\nTo activate the diagnostic mode, use the `--bench` flag. This can be combined with strategy overrides to compare efficiency across different regimes:\n\n```bash\n# Standard execution with real-time metrics\n./push_swap --bench 5 4 3 2 1\n\n# Isolate sorting instructions from statistics\n./push_swap --bench --simple 5 4 3 2 1 2\u003ebench.txt \u003e/dev/null \u0026\u0026 cat bench.txt\ncat stats.txt\n[bench] disorder:  100.0%\n[bench] strategy:  Simple / O(n^2)\n[bench] total_ops: 8\n[bench] sa:  1  sb:  0  ss:  0  pa:  2  pb:  2\n[bench] ra:  1  rb:  0  rr:  0  rra:  2  rrr:  0\n```\n\n### Key Metrics Reported\n\nThe report generated via stderr provides the following technical data:\n\n- **Disorder Percentage**: A perfectly sorted stack returns 0.00%, while a reverse-sorted stack returns 100.00%.\n- **Strategy \u0026 Complexity Class**: Identifies the specific engine chosen by the `Adaptive Selector` (Selection, Sandglass, or Radix) and its asymptotic complexity.\n- **Total Operations**: The final count of all movements.\n- **Individual Instruction Breakdown**: A granular count of every operation used (`sa`, `pb`, `ra`, `rrr`, etc.), allowing for precise bottleneck analysis.\n\n\n## Resources\n\n### Theoretical Documentation\n* [Oceano's Push Swap Notion Site](https://suspectedoceano.notion.site/push_swap-ee2c472005d54d978412bfc37a1ab3e7) - Extensive guide on 42 requirements and project logic.\n\n### Algorithm Deep Dives\n* [Push_swap: Performant Sorting Video](https://www.youtube.com/watch?v=OaG81sDEpVk\u0026t=2945s) - Visual walkthrough of stack coordination and operations.\n* [PUSH_SWAP: the smallest number of movements](https://medium.com/@ridwaneelfilali/push-swap-eff35d3ee0c4) - Explanation of Hourglass algorithm by 42 student B.R.O.L.Y.\n\n### Visualizers\n* [Push_swap Visualizer (o-reo)](https://github.com/o-reo/push_swap_visualizer) - Essential tool for debugging, verifying moves, and seeing the algorithm in real-time.\n\n## Contributions\nIn compliance with the 42 curriculum requirements, the following breakdown outlines the core contributions of each learner:\n\n### jbarreir:\n* Implementation of the Parsing \u0026 Input Validation system (handling quoted strings and mixed arguments).\n* Design of the Doubly Linked List and core stack operations (sa, pa, ra, rra, etc.).\n* Development of the Selection Sort (Simple strategy) and Sandglass Sort (Medium strategy).\n* Design of the --bench mode diagnostic system.\n\n### edsole-a:\n* Design and implementation of the algo_selector and the Disorder Coefficient heuristic.\n* Development of the Radix Sort (Complex strategy) and the stack Normalization logic.\n* Optimization of bitwise operations for large datasets.\n\n### Joint Work:\n* Unified Error Handling and memory leak prevention system.\n\n## AI Usage Disclosure\n\nIn compliance with 42's evaluation standards regarding Artificial Intelligence:\n\n- **Concept Clarification**: AI was used to clarify the mathematical logic behind the algorithms.\n- **Translation \u0026 Localization**: AI assisted in translating technical explanations from Spanish to English to ensure professional documentation standards.\n- **Strict Policy**:\n  - **No Copy-Paste**: No code was directly copied from AI. All implementations were written manually.\n  - **Ownership**: Every line of code was understood and is capable of being replicated or modified by the author during a defense.\n  - **Verification**: AI-generated suggestions were always cross-referenced with official documentation and verified using the testers mentioned in the Resources section.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbarrarrr%2Fpush_swap","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbarrarrr%2Fpush_swap","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbarrarrr%2Fpush_swap/lists"}