Skip to content
Related Articles

Related Articles

Sort an array which contain 1 to n values

Improve Article
Save Article
  • Difficulty Level : Easy
Improve Article
Save Article

You have given an array which contain 1 to n element, your task is to sort this array in an efficient way and without replace with 1 to n numbers.
Examples : 

Input : arr[] = {10, 7, 9, 2, 8, 3, 5, 4, 6, 1};
Output : 1 2 3 4 5 6 7 8 9 10 

Native approach : 
Sort this array with the use of any type of sorting method. it takes O(nlogn) minimum time.

Efficient Approach (Using Cyclic Sort):

Idea: 

The given array contains number in the range [1 to n]  so we can use cyclic sort 

Follow the steps mentioned below to solve the problem

  • Traverse the array 
    • Check if the array is at correct position
    • Else swap the element to the element at its correct position

Below is the code implementation of the above approach:

Java




/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.Arrays;
class GFG {
 
      // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 3, 2, 5, 6, 1, 4 };
         
          // Function call
          sort(arr);
 
        // Printing the answer
        System.out.println(Arrays.toString(arr));
    }
    static void sort(int[] arr)
    {
        int i = 0;
        while (i < arr.length) {
 
            // Finding the correct index
            int correct = arr[i] - 1;
 
            // Element index and value not match
            // then swapping
            if (arr[correct] != arr[i]) {
 
                // Calling swap function
                swap(arr, i, correct);
            }
            else {
                i++;
            }
        }
    }
 
    // Function to swap values
    static void swap(int[] arr, int first, int second)
    {
        int temp = arr[first];
        arr[first] = arr[second];
        arr[second] = temp;
    }
}
// This code is contributed by Karan Hora

Output

[1, 2, 3, 4, 5, 6]

Time Complexity: O(n)
Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!