Unit 11

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

UNIT 11 INTRODUCTION TO DATA

STRUCTURES: ARRAY
Structure
Page No.
1 1.1 Introduction C

Objectives
1 1.2 Program Analysis
1 1.3 Arrays as Data Structures
1 1.4 Creation of Arrays and Elementary Operations
1 1.5 Storage of Arrays in Main Memory
11.6 Sparse Arrays
11.7 Summary
1 1.8 Solutions/Answers

11.1 INTRODUCTION
This Unit is the introductory unit on data structures. In Sec. 11.2, we introduce you to program
analysis and the concept of computational complexity. Since these topics are studied in the
Design and analysis of algorithms course we will not go into great details. In Sec. 11.3, we will
start our study of data structures with the simplest data structure, namely Array. You have
already seen arrays in Unit 6 and Unit 7 of Block 2. In this unit, we are going to look at this
amay as a data structure. In Sec. 11.4 of this Unit, we will see how to create arrays and perfom
some elementary operations on them. In Sec 11.5, we will discuss different ways of storing data
in an array like row major, column major methods. In the last section, Sec 1 1.6, we will discuss
sparse arrays which are large arrays in which most entries are the same, usually 0.

Objectives
After studying this unit, you should be able to
explain the benefits of program analysis;

define a data structure:

perform basic operations on arrays; and

explain how data is stored in sparse arrays.

11.2 PROGRAM ANALYSIS

In this section, we introduce you to program analysis. What do we mean by this? After all,
there are many ways of analyslng a program. For instance, we can analyse a program from any
of the following polnts of view.

i) Verifying that it satisfies the requirements


ii) Proving that it runs correctly without any logical errors.
iii) Determining if it is readable.
1v) Checking that modifications can be made easily, without introducing new errors.

v) We may also analyse program execution time and the storage complexity associated with
it, i.e. how fast does the program run and how much storage it requires.
Data Structures Another related question can be : How big must its data structure be and how many S .....
L G ~ ~

be required to execute its algorithm?

Since this course concerns data representation and writing programs, we shall analyse programs
in terms of storage and time complexity.

Performance Issues
In considering the performance of a program. we are primarily interested in
i) how fast does it run?

ii) how much storage does it use?


Generally we need to analyse efficiencies, when we need to mmpare alternative algorithms and
data representations for the same problem or when we deal with very large p r o g a m .

We often find that we can trade time efficiency for space efficiency, or vice-versa. For finding
any of these i.e. time or space efficiency, we need to have some estimate of the problem size.
Let's assume that some number N represents the size of the problem. The size of the problem or
N can reflect one or more features of the problem, for instance N might be the number of input
data values. or it is the number of elements of an array etc. In the ca5e of algorithms that take
integers as input like the algorithm to find the hcf, it is the number of digits in the input. For
example. N may be the number of names of persons that we want to sort in alphabetical order.

Let us consider an example here. Suppose that we are given two algorithms for finding the
largest value in a list of N numbers. It is also given that second algorithm executes twice the
number of instructions executed by the first algorithm for each N value.

Let first algorithm execute S number of instructions. Then second algorithm would execute 2 s
instructions. If each instruction takes 1 unit of time, say I millisecond then for N = 10, 100,
1000 and 10000 we shall have the number of operations and estimated execution time as given
below:

Algorithm I Algorithm I1
a,
IY
1 Number of 1 Estimated 1 Number of 1 Estimated
Instructions Execution Time Instructions Execution Time
10 10s I0 msec 20s 20 msec
100 100s 100 msec 200s 200 msec
1000 1000s 1000 msec 2000s 2000 msec
10000 IOOOOS 10000 msec 20000s 20000 msec
I millisec = I msec = 111000 sec

You may notice that for larger values of N, the difference between execution time of the two
algorithm 1s appreciable, and one may clearly say that Algorithm I1 is slower than Algorithm 1.
Also, as the problem sizx becomes larger and larger, Algorithm I performs better and better than
Algorithm 11. This kind of performance improvement is termed as order of improvements. Two
algorithm may compare with each other by a constant factor, i.e. improvement from one to
another does not change as the problem size gets larger. For example, one of them can be two
times faster than the other and it always remain two times better regardless of the problem size.

In both the above algorithms, the time taken grows linearly with input size. Actually, instead of
time, we usually talk in terms of the number of basic operations the algorithm has to perform as
a function of the size of the input. For example, to add two n digit integers, the computer has to
perform n operations. We have to add each digit in the first number to the corresponding digit in
the second number. In this case, the number of operations grows linearly with the size of the
input. On the other hand, the usual algorithm for multiplying two n digit numbers performs
about n2 operations. This is because, under the usual multiplication algorithm, we have to
multiply each digit of the first number with the each digit of the second number. See Fig. 1 for
the number of operations required to add and multiply 3 digit numbers. Introduction to Data
Structures: Array

Fig. 1: Number of operations for adding and multiplying two 3 digit numbers.

Therefore, the number of operations required to multiply two n-digit numbers grow as the
square of the size of the numbers. Such algorithms are called quadratic algorithms. What we
are actually doing is to compare the growth rate of algorithms with known functions; in the
above two cases we see that the growth is comparable to a linear polynomial and a quadratic
polynomial, respectively.

There isa standard notation for such comparisons called the big-Oh notation. If f(n) and g(n)
are two functions defined on natural numbers, we say that f(n) = O(g(n)) if If(n)l 5 Klg(n)l
where K is a constant independent of n. If f(n) is the number of operations an algorithm has to
perform on an input of size n, if f(n) = O(n), we say that the algorithm is linear algorithm; if
f(n) = 0 (n2), we say that the algorithm is a quadratic algorithm. More generally, if
f(n) = O(g(n)) for some polynomial g(n), we say that the algorithm is a polynomial time
algorithm. We discuss the analysis(and design) of algorithms in the Design and Analysis of
Algorithms course.

Average Case and Worst Case Analysis

An algorithm chooses an execution path depending on the set of data values (input). Therefore,
an algorithm may perform differently for two different sets of data values. If we take a set of
data values for which the algorithm takes the longest possible execution time, it leads us to the
worst case execution time. On the other hand, an average case execution time is the execution
time takes by algorithm for an expected range of data values. For analysis of an algorithm to
predict its average or worst case execution time, we need to make certain assumption such as
assuming that all operations take about the same amount of time.

For example, suppose we have n student cards with the enrolment numbers al, a2, . . ., a, written
on them and they are in a box. A number is called out and you have to take out the card with
that number. Let us assume that the cards are arranged in ascending order, i.e. that is a, is the
topmost card, a, is the card at the bottom and a, < a,+1 for 1 L: i 5 n - 1. If you do not know
this and you have to search through the cards and find the kthcard, you have to check through k
cards. So, the number of operations you need depends on the card you want to find. In the worst
case, if you want to find the nthcard, you have to search through n cards.

What is the average time ybu take to find any card? Suppose that all the cards are equally
probable to be called. Then, the probability of any card being called out is and the average
A
number of cards you have to search through is Cy=,(i) . since the number of cards you have to
search through to find the ithcard is i. The sum is

One issue we have to deal with when we want to optimise the performance is the representation
of data. We have find a representation that optimises the time(or space) involved in working
with the data. We use Data structures for this. We do not merely want to represent data, but
also work with them. So, our data structures should allow us to perform the required operations
in an efficient way. So, we can say that

Data Structures = Organised Data + Allowed operations


Data Structures In the next section, we begin our study of data structures with arrays, the simplest of data
structures.

11.3 ARRAYS AS DATA STRUCTURES

In applications where we have a small number of items to handle, we tend to specify separate
variables names for each item. When we have to keep track of more pieces of related data, we
need to organise data, in such a way that we can use one name to refer to several items. Let us
see this through a simple example. Consider the following problem:

Read 25 numbers and print them in reverse order.

The problem requires all the numbers as they are read. Further we cannot print anything until all
25 numbers are read; therefore, we need to store all the twenty five numbers. Reading 25
numbers in 25 different variables will be quite cumbersome and so would be writing these
numbers in reverse order. It is much simpler to call the numbers NUMI, NUM2, NUM3, ... ,
NUM2s.

Each number is a NUM and numbers are distinguished by subscripts. Also, they are read in
succession. Thus, we can abbreviate this sequence as NUMi for i = 1,2,. . . ,25. Such a
subscripted variable is called an array. More formally, an array is a finite, ordered set of
homogeneous elements which are stored in adjacent cells in memory. Arrays are usually used
when a program includes a list of recurring elements.

You are probably wondering 'What is new about arrays? We have discussed them already in
Block 2.'. Here, we are going to study array as an abstract object without reference to any
language. The set of integers exists independently of any representation or implementation. In
this set you can cany out basic operations like addition, subtraction, multiplication and division.
The C data type int is a particular implementation of this. It allows you to carry out all the
basic operations like addition, multiplication etc. This is not the full set of integers, but only
integers between -32767 and 32767 according to C89 specification. Similarly, we can think of
an abstract data type called array with a specified set of operations.

One characteristic feature of the array is that it takes the same amount of time to access any
element in the array. As we have seen, in C , elements of an array can be accessed using
subscripts placed in square brackets[]. Repetition over a sequence of values of i may also be
implemented using a loop construct. For example, the following statement reads all 25 values:
for(i = 0;i < 25; ++i)
scanf("%dH,NUM[i]);
A similar approach works out for printing the values.

The simplest form of an array is a one-dimensional array or vector. As stated earlier, the various
elements of an array are distinguished by giving each piece of data separate index or subscript.
The subscript of an element designates its position in array's ordering. An array named A which
consists of N elements can be depicted as shown in Fig. 2.

A[O] A[l] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A[n- 11

Fig. 2: One dimensional array.

Arrays can be multi-dimensional. Any array defined to have more than one dimension is
\
considered to be multi-dimensional array. An array can be 2-dimensional, 3-dimensional,
4-dimensional, or N-dimensional although they rarely exceed three dimensions.
Two-dimensional arrays, sometimes called matrices, are quite common. The best way to think
about a two-dimensional array is to visualise a table of columns and rows: the first dimension in
the array refers to the rows, and the second dimension refers to the columns. Let us see an Introduction to Data
example of a Zdimensional array. Structures: Array

A collection of data about the grades of students in a class in the four different exams can be
represented using a Zdimensional arrays. If we have 10 students and each given grades in 4
exams, we can depict it as in Fig. 3. Each cell in this table contains a grade value for the student

Fig. 3: An example of a two dimensional array.

Number (given by the corresponding row number) and exam number (given by the
corresponding column no.). We may map it on to an array A of order 10 x 4. A [I][ J] In C, we know thatthe row
represents an element of A, where I runs from 1 to 10 and J runs from 1 to 4. A[3] 141 will index runs from 0 to 3 and
have the grade value of 3rd student in fourth exam, A [ 8 ] [I]will have the grade value of 8th the jndex runs

student in first exam, and so on. 0 to 9. More about this later

By convention, the first subscript of a 2-dimensional array refers to a row of the array, while the
second subscript refers to a column of the array.

In general, an array of the order M x N (read as M by N) consists of M rows, N columns and


MN elements. It may be depicted as in Fig. 4 Let us now discuss the syntax and semantics of an

I I I I I I I I

Fig. 4: A 2 dimensional array.

array. We can divide our discussion in three parts:

Array declaration

Storage of Arrays in Main Memory

Use of Arrays in Programs

In the next section, we will discuss creation of arrays and elementary operations that can be
performed on arrays.

11.4 CREATION OF ARRAYS AND ELEMENTARY


OPERATIONS
Three things need to be specified to declare an array in most of the programming languages:
Data Structures the array name

the type of data to be stored in array elements

the subscript range

In C language the array declaration is a follows:

In first declaration A is the array name; the elements of A can hold integer data and the number
of elements is 24 i.e. subscripts range from 0 to 23.

In the next declaration B is the array name; the data type of its elements is real and it is a
2-dimensional array with subscripts ranging from 0 to 99 and 0 to 24. In other languages, the
lower limit on an array does not have to be 1. It makes more sense to start the array at a value
that corresponds to the context of your data. Also, subscript need not always be positive in some
languages. It can be negative or zero. However, not all programming languages allow zero or
negative subscripts.

Be careful when using arrays with indexes beginning with 0. Failing to remember that the zero
elements is the first item in the array - and therefore, the element at index 5 is the sixth, not the
fifth - is a frequent cause of programming bugs.

You can begin your indexes at 0 or at 1 or at any other value, if programming language in use
allows it. There is no technical reason to use one method over the other. However most
programmers prefer to start arrays at 0 -even though it is easier to begin at 1. The reason for
this is that some languages -C and C++ for example - require arrays to begin with zero
indexes. If you define most of your arrays the same way, your programs will be easier to convert
to these languages.

An array declaration tells the computer two major pieces of information about an array. First,
the range of subscripts allow the computer to determine how many memory locations must be
allocated. Second the array type tells the computer how much space is required to hold each
value. Let us consider the following declarations:

The first declaration tells the computer to allocate enough space for the variable A to store 10
integers. The second declaration tells the computer to allocate enough space for the variable B
to store 10 reals. Since a real number takes more space than an integer the storage allocated
would not be same. We have already discussed declaration of arrays in C in Units 12 and 13 of

I
Operations on Arrays

The array is a homogeneous str~rcture,i.e. the elements of an array are of the same type. It is
finite; it has a specified number of elements. An array is ordered; there is an ordering of
i
elements in it as zeroth, first, second etc. Following set of operations are defined for this
structure.

i) Creating an array
ii) Initialising an array

iv) Retrieving an element


v) Inserting an element
0 vi) Deleting an element
vii) Searching for an element Introduction to Data
Structures: Array
viii) Sorting elements
ix) Printing an array

Let us now write a function that deletes an element from an array. The function in Listing 1
takes the name of the array(which is actually a pointer to an int),the index of the element to be
removed and the index of the last element as arguments. It removes the element and returns the
index of the last element.

int delete-element(int *list, int last-index, int index)


I
int i;
for(i = index; i < last-index; i ++)
list [il=list [i+ll;

Let us now see how to insert an element in an array. The function in Listing42takes the name of
the array, the element to be inserted, the index of the last element and the postion where the
element has to be inserted.

int i;
i f ( last-index == max-array-size)(
Error("Array is full. Cannot insert element. ") ;
return (-1);

for ( i = last-index-1; i > index; i--)


list [i+:L]=list [i] ;
list[index]=num;
1
return (last-index+l) ;

Here is an exercise to check vou understanding of our discussion so far.

E l ) Write a program that


1) creates an array consisting of elements 3 , 4 , 5, 6 and 7;
2) removes 5 from the array;
3) inserts 10 after 7 in the array.

We will see how to sort an array of integers using insertion sort.

Example 1: Suppose we want to sort the list 21, 20, 19, 23, 16,25. We do this in 5 passes. In
the first pass, we look at 20 which is less than 21, yet it appears before 20. So, we exchange 20
and 21. In the second pass, we look at the third element in the list, which is 19. We see that the
two elements before it, 21 and 20, are both bigger. So, we move 21 and 20 right by one position
and insert in the position occupied by 21 previously. Now, the first three elements are in the
correct order. We proceed like this to sort all the elements of the list. In general, in the ith pass,
+
insertion sort ensures that all the i 1 elements from ~ o s t i o n 0s through i are in sorted order. In 1
Data Structures
Table 1: Interchanges in pass 2. I

a b l e 2: Insertion sort. 1
Pass 1
Pass 2
Pass 3
Pass 4
Pass 5

the ith pass, we move the (i + element till its correct place. The function Listing 3 finds the
+
correct position of the (i element in the ith pass: ' 1
int find-position(int *list, int pos)
C ,
int j;
for (j = pos; j > 0 && list[j - 11 > list[posl; j--1;
return (j);
I
Listing 3: A function that finds the correct position of an element.

+
After that, we have to insert the (i I)'h element in the correct position. We can now insert the
element in the correct position using the function we wrote for inserting an element in an array.
***
Here is an exercise for you to check your understanding of the previous example.

E2) Write a program that scans an array of integers, sorts them by insertion sort and prints the
sorted array.

E3) We have used two different functions to find the correct position of an element and for
inserting the element. Both can be performed in one go. Write an insertion sort function

These may operations apply to arrays of any dimension. We have already used these operations
in our programme that lists primes. Here is a program that gives examples some of these

1
2
operations.
/*Program 1 1 . 3 : 2-dimensional Array operations'
example. F i l e name: unitll-matrix-ex.c*/
I
3 #include cstdio.h>
4 #define num-rows 4
5 #define n u ~ c o l u m n s4
6 void printarray( int mymat [numrows] [ ~ u L c o ~ u ~ ~ s;] )
7 void findelement ( in t mymat [numrows] [ n u ~ c o l u m n s ], i n t x) ;

10 /+ Create and i n i t i a l i s e an array o f i n t s */


I1 int i, j, mat[nu~rows][nu~columns]= { (1, 0, 0, 0) I;
12 / * p r i n t the array */
13 printf("First call to printarray ...\nu);
14
15
printarray(mat);
/* I n s e r t elements; Make i t 4x4 diagonal matrix */ I
16 for (i = 0; i < num-rows; i++) Introduction to Data
17 f o r (j = 0; j < nuacolumns; j++) Structures: Array
18 {
19 i f (i == j)
20 mat[i][j] = 3;
21 else
22 mat[i][jJ = 0;
23 3
24 printf("\n\nW);
25 printf("Second call to printarray.,.\nn);
26 printarray(mat);
27 for (i = 0; i < nuarows; i++)
28 f o r (j = 0; j < numcolumns; j++)
29 mat[i][j] = i + j;
30 printf("\n\nU);
31 printf("Third call to printarray ...\n");
32 printarray(mat) ;
33 printf("\n\nW) ;
34 findelement(mat, 4 ) ;
35 return (0);
36 3
37 void printarray(int mat[nu~rows][nu~columns])
38 C
39 i n t a, b:
30 for (a = 0; a < n u m o w s ; printf("\nm), a++)
41 for (b = 0; b € numcolumns; b++)

44 void findelement(int mat[numrows][nuacolumns], int x)


45 C
46 Int i, j, found;
47 found = 0;
48 printf("Searching for %d ...\n", x);
49 for (i = 0; i < nunuows; j = 0, i++)
50 {
51 for (j = 0; j < numrows; j++)
52 if (mat[i][j] == x)
53 C
54 found = 1;
55 break ;
56 1
57 if (found == 1)
58 break ;
59 3
60 if (found == 0)
61 printf("Cou1d not find %dm, x);
62 else
63 printf("Found ! mat[%d][%d]=%d\n", i, j, x);
64 1;
Here is the output from the program:

/a4h1tput from Prog 1.1*/ F i r s t c a l l t o printarray ..


mat101 [O]=l, mat[O] [l]=O, mat[O][Z]=O, mat COI [31=O,
mat [I]CO]=O, mat [I][I]=O ,
mat[l] [Z]=O, mat [I][3]=O, mat [Z] [O]=O , mat [2] [ l ] = O ,
mat[Z] [2]=0, mat [ 2 ] [31=0,
mat [3] [0] =O , mat [3] [ l ] = O , mat [3] [2]=0, mat [3] 131=0,
Second c a l l t o printarray ... mat[O][O]=3,
mat[O][l]=O, mat[O1[2]=0,
Data Structures matCO][3]=0, mat [I] [O]=O, mat[l] [1]=3, mat111 [2]=O,
mat[l] [3]=0,
mat[2][0]=0, mat[2][1]=0, mat[2][2]=3, mat[21[31=0,
mat[3][0]=0, mat[3][1]=0,
mat [3] [2]=0, mat [3] [3]=3,
Third call to printarray ... mat[O][O]=O, mat[O][l]=l,
mat [O] [2]=2,
mat [O] [3] =3, mat [I] [O]=l, mat [1] [l]=2, mat [I] 123=3,
mat [I] [3]=4,
mat 121 [O]=2, mat 121 [l]=3, mat [2] [2]=4, mat [2] [3]=5,
mat [3] [0]=3, mat 131 [1]=4,
mat [31[2]=5, mat [3] [3]=6,
16 17 18 19 20 .........
Memory
A[O] A[1] A[2] A[3] A141 .........

each element which is same for all the element of an array. We may call the starting address as a
base address and denote it by B. Then the location of Ith element would be

where S is the size of each element of array. We refer you to the fourth example program in
Unit 12 of Block 2 which illustrates this.

Let us now consider storage mappings for multi-dimensional arrays. As we had seen in previous
section that in a 2-dimensional m a y we think of data being arranged in rows and columns.
However Machine's memory is arranged as a row of memory cells. Thus the rectangular
structure of a 2-dimensional array must be simulated. We first calculate the amount of storage
area needed and allocate a block of contiguous memory cells of that size. One way to store the
data in the cells is row by row. That is, we store first the first row of the array, then the second
row of the array and then the next and so on. For example, the array defined by A which
logically appears as given in Fig. 5 appears physically as given in Fig. 7. Such a storage scheme
is called Row Major Order.

The other alternative is to store the array column by column. It is called Column Major Order.
The array of Fig. 8 on the next page shows the physical arrangement in Column Major order.

E6) Create a two-dimensional array whose number of rows are 10 and columns are 26 and the
component type is character.

E7) Show how the array

would appear in the memory when stored in


i) Row major order

ii) Column major order


In all implementations of C the storage allocation scheme used is the Row Major Order.

Let us now see how do we calculate the address of an element of a 2-dimensional array, which
is mapped in Row Major Order. Consider a 4 x 6 array A[4] [6]. Take B as the array's base
address and S as the size of element of the array.

Remember that in C, array indices start with 0. So, to locate element A [ I ] [J] we must skip I
rows(0,1,2,. . . , I - 1); each having 6 elements, each element of length S and (J) elements of Ith
row, each of length S, Therefore, the address of element A [ I ] [J] would be

We may now generalise this expression for a Zdimensional array

where Uo - 1 and UI - 1 are the upper bounds of the two subscript ranges.

The location of an element A [ I ] [ J] for such an array would be

The row major order varies the subscripts in right to left ordel: For example, the elements of a
2-dimensional array AIUI,Uzl would be stored in following order:

A[Uj - l , U z - 11
We may generalise it for an N-dimensional array AIUo]AIUl]. . .A[Un - I]. The elements would
be stored in following order:

AIUo - I]AIUI - I ] . . .A[U, - 11


I Data Structures as time if we use the usual methods for working with these arrays. We will look at some special
methods for re~resentingand workine with these matrices.

I1
We shall discuss only the first representation here in this Unit. The Linked List representation
shall be discussed in a later Unit.

Each element of a 2-dimensional array is uniquely characterised by its row and column position.
We may, therefore, store a sparse array in another array of the form.

The sparse array given in Fig. 9 may be stored in the array A[7:)[3]as shown in Fig. 10. The 1

Fig. 10: Sparse array representation using vector representation.

Elements A[O][O] and A[O:I[l] contain the number of rows and columns of the sparse array.
1
A[0][2] contains the number of non-zero elements of sparse array. The first and second element
of each of the rows store the number of row and column of the non-zero term and the third
element stores the value of non-zero term. In other words, each non-zero element in a
Intmductiontoh
2-dimensional sparse array is represented as a triplet with the format (row subscript, column
Structures: Array
subscript, value).

If the sparse array was one-dimensional, each non-zero element would be represented by a pair.
In general for an N-dimensional sparse array, nnn-zero elements are represented by an entry
with N + l values.

If you are interested in alternate representations of sparse matrices and methods for working
with them, you may refer to Sec. 2.7 in the book 'Numerical recipes in C' and the references
given there.

11.7 SUMMARY
In this Unit, we saw
% i) the benefits of program analysis.
ii) the definition of a data structure
iii) how to perform basic operations on arrays
t
iv) how data is stored in sparse arrays
1I
Ii 118 SOLUTIONSIANSWERS

El) /*Program 11.1.A simple example of Array operations


File name: unitll-insert-element.c*/
#include Cstdio.h>
#define max-array-size 20
void Error(char message) ;
void Message(char *message);
i int printarray(int *list,int limit);
int delete-element(int *list, int last-index, int index):

1 int a[max-arrav-sizel=f3.4.5.6.71.
- . , .-, , last = 5:
- a ,

printarray(a,last) ;
last = delete_element(a,last,2);
Message("After deleting 5 the array is:");
printarray(a,last);
last = insert-element(a.lO.last.4):
, -,.
Message("After inserting 10 in the fifth position \
the array is:" ) ;
printarray(a,last);
return (0);
I
void Error (char *message)

int printarray(int *list,int last)


{
int i;
for(i = 0; i < last; i++)
printf("%d\nV, list[i]);
return (0);
3
i n t delete-element ( in t *list, in t last-index, in t index)
C
int i;
for(i = index; i < last-index; i ++)
list[i]=list[i+l];
return (last-index-1);
1
int insert-element(int *list, int num, int last-index,
int index)
{
Int i;
i f ( last-index == ma~array-size){
Error("Array is full. Cannot insert element.");
return (-1);
1
else {
( i = last-index-1; i > index; i--)
for
list[i+l]=list[i];
list[indexl=num;
3
return (last-index+l) ;
1
E 2 ) /*Program 1 1 . 2 . A example t o show s o r t i n g o f a r r a y s .
I n s e r t i o n s o r t . F i l e name: u n i t l l - i n s o r t n . c*/
#include <stdio.h>
#defl ne max-array-size 20
int find-position(int *a, int num);
int insert-number(int *a, int cpos, int npos, int num);
int main()
C
int i, k = 0, array[max_array-size] = ( 0 3, list-size;
printf("Enter the size of the list:\nU);
scanf("%dW, &list-size);
printf("Enter the elements of the array:\nU);
for (i = 0 ; i < list-size; i++)
scanf("%d", &array[i]);
for (i = 1;i < list-size; it+) (
k = find-position(array, i);
if (k != i)
insert-number(array, i, k, array[il);
1
printf("The sorted array is:\nn);
for (i = 0; i < list-size; i++)
printf("%d\n", array[i]);
return (0);
3
int find-position(int *list, int pos)
int j;
for (j = pos; j > 0 && list[j - 11 > listCpos1; j--1;
return (j);
1
int insertnumber(1nt *list, int cpos, int npos, int num)
/* cpos i s the current p o s i t i o n o f num;
npos i s t h e new p o s i t i o n o f num*/
C
int i;
/ * S h i f t elements t o the r i g h t b y one place*/
for (i = cpos; i > npos; i--1
listli] = list[i - 11; Introduction to Data '
nsert the number a t the new position. */ Structures: Array
list[nposl = num;
return 0;

E3) i n t
C
int cp, j, temp;
for (cp = 1; cp < LL; cp++)

temp = list[cp] ;
tor (j = cp; j > 0 && 1
listCj] = list[ j -
list[j] = temp;

return (0);

You might also like