How to sort an array in a single loop? - GeeksforGeeks

11 Jun, 2021
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:  
Selection Sort
Binary Sort
Merge Sort
Radix Sort
Insertion Sort, etc
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++
Java
Python3
C#
Javascript
// 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 loopint *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 codeint 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 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 code to sort an array of integers# with the help of single loop # Function for Sorting the array# using a single loopdef 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 Codeif __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# code to sort an array of integers// with the help of single loopusing 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
<script>// Javascript code to sort an array of integers// with the help of single loop // Function for Sorting the array    // using a single loopfunction sortArrays(arr){     // Finding the length of array 'arr'        let length = arr.length;           // Sorting using a single loop        for (let 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.                let 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 methodlet arr=[1, 2, 99, 9, 8,                      7, 6, 0, 5, 4, 3];document.write("Original array: ["                           + (arr).join(", ")+"]<br>");// Sorting the array using a single looparr = sortArrays(arr); // Printing the sorted array.document.write("Sorted array: ["                   + arr.join(", ")+"]<br>"); // This code is contributed by patel2127</script>
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++
Java
Python3
C#
Javascript
// 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 loopchar* 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 codeint 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 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 code to sort an array of Strings# with the help of single loop # Function for Sorting the array using a single loopdef 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 Stringgeeks = "GEEKSFORGEEKS"n = len(geeks) # declaring character arrayarr=[0]*n # copying the contents of the# string to char arrayfor 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 loopansarr = 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# code to sort an array of Strings// with the help of single loopusing 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
<script> // JavaScript code to sort an array of integers// with the help of single loop // Function for Sorting the array// using a single loopfunction sortArrays(arr){         // Finding the length of array 'arr'        let length = arr.length;         // Sorting using a single loop        for (let j = 0; j < length - 1; j++)        {             // Type Conversion of char to int.            let d1 = arr[j];            let d2 = arr[j + 1];             // Comparing the ascii code.            if (d1 > d2)            {                 // Swapping of the characters                let temp = arr[j];                arr[j] = arr[j + 1];                arr[j + 1] = temp;                j = -1;            }        }        return arr;    }             // Declaring a String        let geeks = "GEEKSFORGEEKS";         // Declaring a character array        // to store characters of geeks in it.        let arr = geeks.split("");      document.write("Original array: ["                           + arr.join(", ")+"]<br>");// Sorting the array using a single looparr = sortArrays(arr); // Printing the sorted array.document.write("Sorted array: ["                   + (arr).join(", ")+"]<br>");               // This code is contributed by shivanisinghss2110 </script>
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.
 
mohit kumar 29
Rajput-Ji
princiraj1992
SHUBHAMSINGH10
patel2127
shivanisinghss2110
Sorting
Technical Scripter
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
C++ Program for QuickSort
Stability in sorting algorithms
Quick Sort vs Merge Sort
Sorting in Java
Quickselect Algorithm
Recursive Bubble Sort
Check if two arrays are equal or not
Longest Common Prefix using Sorting
Python | Sort a List according to the Length of the Elements