OneBite.Dev - Coding blog in a bite size

sort items in array by asc in C

Code snippet on how to sort items in array by asc in C

  void asc_sort(int arr[], int n) 
 { 
     int i, j, temp; 
     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; 
                } 
            } 
        } 
 } 

This code uses a bubble sort algorithm to sort items in an array in ascending order. It has two for loops - the outer one loops over each item in the array, and the inner one loops over all the items after the current item. If the item after the current item is larger, the two items are swapped. The outer loop terminates when it has compared the last two items, meaning the array is now sorted in ascending order.

c