Sort an Array Containing 1 to N Values



Sorting an array containing values from 1 to n means arranging the integers in their natural ascending order. This type of sorting problem is commonly encountered in competitive programming (for solving complex problems), where the array is guaranteed to have integers ranging from 1 to n.

In this article, we will explore various approaches to solving this problem. In this problem, we are given an array containing values ranging from 1 to n in random order. Our goal is to sort the array in ascending order.

Example 1

  • Input: int array[] = {3, 1, 2, 5, 4};
  • Output: 1, 2, 3, 4, 5

Explanation:

The sorted array of the given array is: {1, 2, 3, 4, 5}

Example 2

  • Input: int array[] = {6, 4, 8, 2, 1, 5, 3, 9, 7};
  • Output: 1, 2, 3, 4, 5, 6, 7, 8, 9

Explanation:

The sorted array of the given array is: {1, 2, 3, 4, 5, 6, 7, 8, 9}

Below are different approaches for Sorting an array that contains 1 to N Values

Brute Force Approach (Different Sorting Techniques)

In this approach, we can use any traditional sorting algorithm like Bubble Sort, Selection Sort, or Insertion Sort. These methods are easy to implement but may not be the most efficient for large arrays.

Steps for Implementation

  • Use a nested loop to compare adjacent elements.
  • Swap them if they are in the wrong order.
  • Continue until the entire array is sorted.

C++ Implementation Code

#include<bits/stdc++.h>
using namespace std;

void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                swap(arr[j], arr[j + 1]);
            }
        }
    }
}

int main() {
    int arr[] = {3, 1, 2, 5, 4};
    int n = 5;
    bubbleSort(arr, n);
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    return 0;
}

Java Implementation Code

import java.util.Arrays;

public class BubbleSort {
    static void bubbleSort(int arr[]) {
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }

    public static void main(String args[]) {
        int arr[] = {3, 1, 2, 5, 4};
        bubbleSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}

Python Implementation Code

def bubble_sort(arr):
    n = len(arr)
    for i in range(n - 1):
        for j in range(n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]

arr = [3, 1, 2, 5, 4]
bubble_sort(arr)
print(arr)

JavaScript Implementation Code

let arr = [3, 1, 2, 5, 4];

function bubbleSort(arr) {
    let n = arr.length;
    for (let i = 0; i < n - 1; i++) {
        for (let j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
            }
        }
    }
}

bubbleSort(arr);
console.log(arr.join(" "));

C# Implementation Code

using System;

class BubbleSortExample {
    static void BubbleSort(int[] arr) {
        int n = arr.Length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }

    static void Main() {
        int[] arr = { 3, 1, 2, 5, 4 };
        BubbleSort(arr);
        Console.WriteLine(string.Join(" ", arr));
    }
}

PHP Implementation Code

<?php
function bubbleSort(&$arr) {
    $n = count($arr);
    for ($i = 0; $i < $n - 1; $i++) {
        for ($j = 0; $j < $n - $i - 1; $j++) {
            if ($arr[$j] > $arr[$j + 1]) {
                $temp = $arr[$j];
                $arr[$j] = $arr[$j + 1];
                $arr[$j + 1] = $temp;
            }
        }
    }
}

$arr = [3, 1, 2, 5, 4];
bubbleSort($arr);
echo implode(" ", $arr);
?>

Output

1 2 3 4 5

Using Built-in Sorting Functions

In this approach, we use an in-built function which sorts the given array. In-built functions use efficient sorting algorithms such as Quicksort, MergeSort, or Trim Sort. This in-built function has a time complexity of O(N log N).

C++ Implementation Code

#include<bits/stdc++.h>
using namespace std;

int main() {
    vector<int> arr = {3, 1, 2, 5, 4};
    sort(arr.begin(), arr.end());
    for (int num : arr) cout << num << " ";
    return 0;
}

Java Implementation Code

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] arr = {3, 1, 2, 5, 4};
        Arrays.sort(arr);
        
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}

Python Implementation Code

arr = [3, 1, 2, 5, 4]
arr.sort()

for num in arr:
    print(num, end=" ")

JavaScript Implementation Code

let arr = [3, 1, 2, 5, 4];
arr.sort((a, b) => a - b);

console.log(arr.join(" "));

C# Implementation Code

using System;

class Program {
    static void Main() {
        int[] arr = {3, 1, 2, 5, 4};
        Array.Sort(arr);

        foreach (int num in arr) {
            Console.Write(num + " ");
        }
    }
}

PHP Implementation Code

<?php
$arr = [3, 1, 2, 5, 4];
sort($arr);

foreach ($arr as $num) {
    echo $num . " ";
}
?>

Output

1 2 3 4 5

Cyclic Sort (Optimal for 1 to N)

This approach is more efficient if the given numbers are from 1 to N. We use the cyclic sort method. This approach sorts the given array in O(N) time complexity and O(1) space complexity.

Steps for Implementation

  • Iterate through the array.
  • If the current element is not at its correct position, swap it with the element at its correct position.
  • Repeat until all elements are correctly placed.

C++ Implementation Code

#include<bits/stdc++.h>
using namespace std;

void cyclicSort(vector<int>& arr) {
    int i = 0;
    while (i < arr.size()) {
        int correct = arr[i] - 1;
        if (arr[i] != arr[correct]) {
            swap(arr[i], arr[correct]);
        } else {
            i++;
        }
    }
}

int main() {
    vector<int> arr = {3, 1, 2, 5, 4};
    cyclicSort(arr);
    for (int num : arr) cout << num << " ";
    return 0;
}

Java Implementation Code

import java.util.Arrays;

public class Main {
    public static void cyclicSort(int[] arr) {
        int i = 0;
        while (i < arr.length) {
            int correct = arr[i] - 1;
            if (arr[i] != arr[correct]) {
                int temp = arr[i];
                arr[i] = arr[correct];
                arr[correct] = temp;
            } else {
                i++;
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {3, 1, 2, 5, 4};
        cyclicSort(arr);
        
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}

Python Implementation Code

def cyclic_sort(arr):
    i = 0
    while i < len(arr):
        correct = arr[i] - 1
        if arr[i] != arr[correct]:
            arr[i], arr[correct] = arr[correct], arr[i]
        else:
            i += 1

arr = [3, 1, 2, 5, 4]
cyclic_sort(arr)

print(" ".join(map(str, arr)))

JavaScript Implementation Code

function cyclicSort(arr) {
    let i = 0;
    while (i < arr.length) {
        let correct = arr[i] - 1;
        if (arr[i] !== arr[correct]) {
            [arr[i], arr[correct]] = [arr[correct], arr[i]];
        } else {
            i++;
        }
    }
}

let arr = [3, 1, 2, 5, 4];
cyclicSort(arr);
console.log(arr.join(" "));

C# Implementation Code

using System;

class Program {
    static void CyclicSort(int[] arr) {
        int i = 0;
        while (i < arr.Length) {
            int correct = arr[i] - 1;
            if (arr[i] != arr[correct]) {
                int temp = arr[i];
                arr[i] = arr[correct];
                arr[correct] = temp;
            } else {
                i++;
            }
        }
    }

    static void Main() {
        int[] arr = {3, 1, 2, 5, 4};
        CyclicSort(arr);

        foreach (int num in arr) {
            Console.Write(num + " ");
        }
    }
}

PHP Implementation Code

<?php
function cyclicSort(&$arr) {
    $i = 0;
    while ($i < count($arr)) {
        $correct = $arr[$i] - 1;
        if ($arr[$i] != $arr[$correct]) {
            list($arr[$i], $arr[$correct]) = array($arr[$correct], $arr[$i]);
        } else {
            $i++;
        }
    }
}

$arr = [3, 1, 2, 5, 4];
cyclicSort($arr);

echo implode(" ", $arr);
?>

Output

1 2 3 4 5
Updated on: 2025-03-19T18:54:21+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements