In C programming write a function SortIntArray which takes a

In C programming write a function

SortIntArray which takes an integer array and an integer n and sorts the first n elements of the array from smallest to largest. Note that the array must be declared as n or larger in size. Hint: there are many ways to sort an array, but perhaps the most straightforward is to use a bubble sort, which uses two nested loops and tests array element i is less than i+1. If the test is false then it swaps those two values, by storing element i in a temporary variable, setting element i to the value of element i+1 and then setting element i+1 to the value in the temporary variable. Note that your array index should never be below 0 or greater than n; In the simplest way to do a bubble sort you perform n-1 tests (inner loop), and you do those n-1 tests n times (outer loop).

Solution

// C code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void sortIntArray(int array[], int n)
{
   int i, j;
   // iterate over array till n-1
   for (i = 0; i < n-1; i++)    
   {
       // Last i elements are already in place
       for (j = 0; j < n-i-1; j++)
       {    if (array[j] > array[j+1])
            {
               // swap elements
                int temp = array[j];
                array[j] = array[j+1];
                array[j+1] = temp;
            }
       }
   }
}

int main()
{
   int array[] = {4,1,5,2,3};
   int size = sizeof(array)/sizeof(array[0]);
   int i,n = 4;
   sortIntArray(array, n);
   printf(\"Sorted array till n: \ \");
   for (i = 0; i < size; ++i)
   {
      printf(\"%d \",array[i]);
   }
   printf(\"\ \");
   return 0;
}


/*
output:

Sorted array till n:
1 2 4 5 3

*/

In C programming write a function SortIntArray which takes an integer array and an integer n and sorts the first n elements of the array from smallest to larges

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site