Array with function and
sorting
Passing array to function
To pass an array to a function , it is sufficient
to list the name of array without any
subscripts , and the size of array as
arguments .
Example 1
void printarray (int arg[], int length)
{
for (int n=0; n<length; n++)
Printf(“%d\n” , arg[n]);
}
int main ()
{
int firstarray[] = {5, 10, 15};
int secondarray[] = {2, 4, 6, 8, 10};
printarray (firstarray,3);
printarray (secondarray,5);
return 0; }
Example 2
#include <stdio.h>
int addNumbers(int fiveNumbers[]);
/*declare function */
int main()
{
int array[5];
int i;
• printf("Enter 5 integers separated by
spaces:");
• for(i=0 ; i<5 ; i++)
• { scanf("%d", &array[i]); }
• printf("\nTheir sum is: %d\n",
addNumbers(array));
• }
int addNumbers(int fiveNumbers[])
{ /* define function */
int sum = 0;
int i;
for(i=0 ; i<5 ; i++)
{ sum+=fiveNumbers[i]; /* work out the total
*/ } return sum; /* return the total */ }
Bubble sort
• Compares adjacent array elements
– Exchanges their values if they are out of order
• Smaller values bubble up to the top of the
array
– Larger values sink to the bottom
Another example
1 2 3 4 5 6
42 35 12 77 5 101
1 2 3 4 5 6
35 12 42 5 77 101
1 2 3 4 5 6
12 35 5 42 77 101
1 2 3 4 5 6
12 5 35 42 77 101
1 2 3 4 5 6
5 12 35 42 77 101
Another example
First Pass:
( 5 1 4 2 8 ) ( 1 5 4 2 8 ), Here, algorithm
compares the first two elements, and swaps
them.
( 1 5 4 2 8 ) ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) ( 1 4 2 5 8 ), Now, since these
elements are already in order (8 > 5).
algorithm does not swap them.
Second Pass:
(14258)(14258)
(14258)(12458)
(12458)(12458)
(12458)(12458)
Now, the array is already sorted, but our
algorithm does not know if it is completed.
The algorithm needs one whole pass
without any swap to know it is sorted.
Third Pass:
(12458)(12458)
(12458)(12458)
(12458)(12458)
(12458)(12458)
Finally, the array is sorted, and the
algorithm can terminate.
Bubble sort program
Main()
{
Int array[100] , n ;
Printf(“enter n\n”);
Scanf(“%d”, &n);
For(i=0;i<n;i++)
{
Scanf(“%d” ,&array[i]);
• for(i = 0; i < n; i++)
• {
• for(j = 0; j < n-1; j++)
• {
• if(array[j] > array[j+1])
• {
• temp = array[j+1];
• array[j+1] = array[j];
• array[j] = temp;
• }
• }
• }
• Printf(“\n the sorted array is\n “);
•
for(i=0;i<n;i++)
{
Printf(“%d\n” , array[i]);
}
Getch();
}