Skip to content
Related Articles

Related Articles

How to sort an array in a single loop?
  • Last Updated : 27 Mar, 2020

Given an array of size N, the task is to sort this array using a single loop.

How the array is sorted usually?
There are many ways by which the array can be sorted in ascending order, like:

In any of these methods, more than 1 loops is used.

Can the array the sorted using a single loop?
Since all the known sorting methods use more than 1 loop, it is hard to imagine to do the same with a single loop. Practically, it is not impossible to do so. But doing so won’t be the most efficient.

Example 1: Below code will sort an array with integer elements.



C++




// C++ code to sort an array of integers
// with the help of single loop
#include<bits/stdc++.h>
using namespace std;
  
// Function for Sorting the array
// using a single loop
int *sortArrays(int arr[], int length)
{
      
    // Sorting using a single loop
    for (int j = 0; j < length - 1; j++) 
    {
        // Checking the condition for two
        // simultaneous elements of the array
        if (arr[j] > arr[j + 1]) 
        {
            // Swapping the elements.
            int temp = arr[j];
            arr[j] = arr[j + 1];
            arr[j + 1] = temp;
              
            // updating the value of j = -1
            // so after getting updated for j++
            // in the loop it becomes 0 and
            // the loop begins from the start.
            j = -1;
        }
    }
    return arr;
}
  
// Driver code
int main()
{
    // Declaring an integer array of size 11.
    int arr[] = { 1, 2, 99, 9, 8,
                7, 6, 0, 5, 4, 3 };
                  
    // Printing the original Array.
    int length = sizeof(arr)/sizeof(arr[0]);
    string str;
    for (int i: arr)
    {
        str += to_string(i)+" ";
    }
    cout<<"Original array: ["
                    << str << "]" << endl;
      
    // Sorting the array using a single loop
    int *arr1;
    arr1 = sortArrays(arr, length);
      
    // Printing the sorted array.
    string str1;
    for (int i = 0; i < length; i++)
    {
        str1 += to_string(arr1[i])+" ";
    }
    cout << "Sorted array: ["
                    << (str1) << "]";
}
  
// This code is contributed by Rajout-Ji


Java




// Java code to sort an array of integers
// with the help of single loop
  
import java.util.*;
  
class Geeks_For_Geeks {
  
    // Function for Sorting the array
    // using a single loop
    public static int[] sortArrays(int[] arr)
    {
  
        // Finding the length of array 'arr'
        int length = arr.length;
  
        // Sorting using a single loop
        for (int j = 0; j < length - 1; j++) {
  
            // Checking the condition for two
            // simultaneous elements of the array
            if (arr[j] > arr[j + 1]) {
  
                // Swapping the elements.
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
  
                // updating the value of j = -1
                // so after getting updated for j++
                // in the loop it becomes 0 and
                // the loop begins from the start.
                j = -1;
            }
        }
  
        return arr;
    }
  
    // Declaring main method
    public static void main(String args[])
    {
        // Declaring an integer array of size 11.
        int arr[] = { 1, 2, 99, 9, 8,
                      7, 6, 0, 5, 4, 3 };
  
        // Printing the original Array.
        System.out.println("Original array: "
                           + Arrays.toString(arr));
  
        // Sorting the array using a single loop
        arr = sortArrays(arr);
  
        // Printing the sorted array.
        System.out.println("Sorted array: "
                           + Arrays.toString(arr));
    }
}


Python3




# Python3 code to sort an array of integers
# with the help of single loop
  
# Function for Sorting the array
# using a single loop
def sortArrays(arr):
  
    # Finding the length of array 'arr'
    length = len(arr)
  
    # Sorting using a single loop
    j = 0
  
    while j < length - 1:
  
        # Checking the condition for two
        # simultaneous elements of the array
        if (arr[j] > arr[j + 1]):
  
            # Swapping the elements.
            temp = arr[j]
            arr[j] = arr[j + 1]
            arr[j + 1] = temp
  
            # updating the value of j = -1
            # so after getting updated for j++
            # in the loop it becomes 0 and
            # the loop begins from the start.
            j = -1
        j += 1
  
    return arr
  
# Driver Code
if __name__ == '__main__':
      
    # Declaring an integer array of size 11.
    arr = [1, 2, 99, 9, 8
           7, 6, 0, 5, 4, 3]
  
    # Printing the original Array.
    print("Original array: ", arr)
  
    # Sorting the array using a single loop
    arr = sortArrays(arr)
  
    # Printing the sorted array.
    print("Sorted array: ", arr)
  
# This code is contributed by Mohit Kumar


C#




// C# code to sort an array of integers
// with the help of single loop
using System;
  
class GFG
{
  
    // Function for Sorting the array
    // using a single loop
    public static int[] sortArrays(int[] arr)
    {
  
        // Finding the length of array 'arr'
        int length = arr.Length;
  
        // Sorting using a single loop
        for (int j = 0; j < length - 1; j++)
        {
  
            // Checking the condition for two
            // simultaneous elements of the array
            if (arr[j] > arr[j + 1])
            {
  
                // Swapping the elements.
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
  
                // updating the value of j = -1
                // so after getting updated for j++
                // in the loop it becomes 0 and
                // the loop begins from the start.
                j = -1;
            }
        }
        return arr;
    }
  
    // Driver Code
    public static void Main(String []args)
    {
        // Declaring an integer array of size 11.
        int []arr = { 1, 2, 99, 9, 8,
                    7, 6, 0, 5, 4, 3 };
  
        // Printing the original Array.
        Console.WriteLine("Original array: " +
                           String.Join(", ", arr));
  
        // Sorting the array using a single loop
        arr = sortArrays(arr);
  
        // Printing the sorted array.
        Console.WriteLine("Sorted array: "
                           String.Join(", ", arr));
    }
}
  
// This code is contributed by Rajput-Ji


Output:

Original array: [1, 2, 99, 9, 8, 7, 6, 0, 5, 4, 3]
Sorted array: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 99]

Example 2: Below code will sort an array of Strings.

C++




// C++ code to sort an array of Strings
// with the help of single loop
#include<bits/stdc++.h>
using namespace std;
  
// Function for Sorting the array using a single loop
char* sortArrays(char arr[], int length)
{
    // Sorting using a single loop
    for (int j = 0; j < length - 1; j++) 
    {
          
        // Type Conversion of char to int.
        int d1 = arr[j];
        int d2 = arr[j + 1];
          
        // Comparing the ascii code.
        if (d1 > d2) 
        {
              
            // Swapping of the characters
            char temp = arr[j];
            arr[j] = arr[j + 1];
            arr[j + 1] = temp;
            j = -1;
        }
    }
    return arr;
}
  
// Driver code
int main()
{
      
    // Declaring a String
    string geeks = "GEEKSFORGEEKS";
    int n = geeks.length();
      
    // declaring character array 
    char arr[n]; 
      
    // copying the contents of the 
    // string to char array 
    for(int i = 0; i < n; i++)
    {
        arr[i] = geeks[i];
    }
      
    // Printing the original Array.
    cout<<"Original array: [";
    for(int i = 0; i < n; i++)
    {
        cout << arr[i];
        if(i + 1 != n)
        cout<<", ";
    
    cout << "]" << endl;
      
    // Sorting the array using a single loop
    char *ansarr;
    ansarr = sortArrays(arr, n);
      
    // Printing the sorted array.
    cout << "Sorted array: [";
    for(int i = 0; i < n; i++)
    {
        cout << ansarr[i];
        if(i + 1 != n)
        cout << ", ";
    
    cout << "]" << endl;
}
  
// This code is contributed by Rajput-Ji


Java




// Java code to sort an array of Strings
// with the help of single loop
  
import java.util.*;
  
class Geeks_For_Geeks {
  
    // Function for Sorting the array using a single loop
    public static char[] sortArrays(char[] arr)
    {
  
        // Finding the length of array 'arr'
        int length = arr.length;
  
        // Sorting using a single loop
        for (int j = 0; j < arr.length - 1; j++) {
  
            // Type Conversion of char to int.
            int d1 = arr[j];
            int d2 = arr[j + 1];
  
            // Comparing the ascii code.
            if (d1 > d2) {
  
                // Swapping of the characters
                char temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                j = -1;
            }
        }
  
        return arr;
    }
  
    // Declaring main method
    public static void main(String args[])
    {
  
        // Declaring a String
        String geeks = "GEEKSFORGEEKS";
  
        // Declaring a character array
        // to store characters of geeks in it.
        char arr[] = geeks.toCharArray();
  
        // Printing the original Array.
        System.out.println("Original array: "
                           + Arrays.toString(arr));
  
        // Sorting the array using a single loop
        arr = sortArrays(arr);
  
        // Printing the sorted array.
        System.out.println("Sorted array: "
                           + Arrays.toString(arr));
    }
}


Python3




# Python3 code to sort an array of Strings
# with the help of single loop
  
# Function for Sorting the array using a single loop
def sortArrays(arr, length):
      
    # Sorting using a single loop
    j = 0
    while(j < length - 1):
          
        # Type Conversion of char to int.
        d1 = arr[j]
        d2 = arr[j + 1]
          
        # Comparing the ascii code.
        if (d1 > d2):
              
            # Swapping of the characters
            temp = arr[j]
            arr[j] = arr[j + 1]
            arr[j + 1] = temp
            j = -1
        j += 1
    return arr
  
# Driver code
  
# Declaring a String
geeks = "GEEKSFORGEEKS"
n = len(geeks)
  
# declaring character array 
arr=[0]*n
  
# copying the contents of the 
# string to char array 
for i in range(n):
    arr[i] = geeks[i]
      
# Printing the original Array.
print("Original array: [",end="")
  
for i in range(n):
    print(arr[i],end="")
      
    if (i + 1 != n):
        print(", ",end="")
   
print("]")
  
# Sorting the array using a single loop
ansarr = sortArrays(arr, n)
  
# Printing the sorted array.
print("Sorted array: [",end="")
  
for i in range(n):
    print(ansarr[i],end="")
      
    if (i + 1 != n):
        print(", ",end="")
   
print("]")
  
# This code is contributed by shubhamsingh10


C#




// C# code to sort an array of Strings
// with the help of single loop
using System;
  
class GFG 
{
  
    // Function for Sorting the array
    // using a single loop
    public static char[] sortArrays(char[] arr)
    {
  
        // Finding the length of array 'arr'
        int length = arr.Length;
  
        // Sorting using a single loop
        for (int j = 0; j < arr.Length - 1; j++) 
        {
  
            // Type Conversion of char to int.
            int d1 = arr[j];
            int d2 = arr[j + 1];
  
            // Comparing the ascii code.
            if (d1 > d2)
            {
  
                // Swapping of the characters
                char temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                j = -1;
            }
        }
        return arr;
    }
  
    // Declaring main method
    public static void Main(String []args)
    {
  
        // Declaring a String
        String geeks = "GEEKSFORGEEKS";
  
        // Declaring a character array
        // to store characters of geeks in it.
        char []arr = geeks.ToCharArray();
  
        // Printing the original Array.
        Console.WriteLine("Original array: ["
                           String.Join(", ", arr) + "]");
  
        // Sorting the array using a single loop
        arr = sortArrays(arr);
  
        // Printing the sorted array.
        Console.WriteLine("Sorted array: ["
                           String.Join(", ", arr) + "]");
    }
}
  
// This code is contributed by PrinciRaj1992


Output:

Original array: [G, E, E, K, S, F, O, R, G, E, E, K, S]
Sorted array: [E, E, E, E, F, G, G, K, K, O, R, S, S]

Is sorting array in single loop better than sorting in more than one loop?
Sorting in a single loop, though it seems to be better, is not an efficient approach. Below are some points to be taken into consideration before using single loop sorting:

  • Using a single loop only helps in shorter code
  • The time complexity of the sorting does not change in a single loop (in comparison to more than one loop sorting)
  • Single loop sorting shows that number of loops has little to do with time complexity of the algorithm.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :