How to sort an array in a single loop ? | C ++ code to sort an array of integers with the help of single loop ; Function for Sorting the array using a single loop ; Sorting using a single loop ; Checking the condition for two simultaneous elements of the array ; Swapping the elements . ; 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 . ; Driver code ; Declaring an integer array of size 11. ; Printing the original Array . ; Sorting the array using a single loop ; Printing the sorted array .
#include <bits/stdc++.h> NEW_LINE using namespace std ; int * sortArrays ( int arr [ ] , int length ) { for ( int j = 0 ; j < length - 1 ; j ++ ) { if ( arr [ j ] > arr [ j + 1 ] ) { int temp = arr [ j ] ; arr [ j ] = arr [ j + 1 ] ; arr [ j + 1 ] = temp ; j = -1 ; } } return arr ; } int main ( ) { int arr [ ] = { 1 , 2 , 99 , 9 , 8 , 7 , 6 , 0 , 5 , 4 , 3 } ; int length = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; string str ; for ( int i : arr ) { str += to_string ( i ) + " ▁ " ; } cout << " Original ▁ array : ▁ [ " << str << " ] " << endl ; int * arr1 ; arr1 = sortArrays ( arr , length ) ; string str1 ; for ( int i = 0 ; i < length ; i ++ ) { str1 += to_string ( arr1 [ i ] ) + " ▁ " ; } cout << " Sorted ▁ array : ▁ [ " << ( str1 ) << " ] " ; }