Data Strcture Array
Data Strcture Array
Array is a container which can hold a fix number of items and these items should be of the same type. Most of
the data structures make use of arrays to implement their algorithms. Following are the important terms to
understand the concept of Array.
Element − Each item stored in an array is called an element.
Index − Each location of an element in an array has a numerical index, which is used to identify
the element.
Array Representation
Arrays can be declared in various ways in different languages. For illustration, let's take C array declaration.
Arrays can be declared in various ways in different languages. For illustration, let's take C array declaration.
As per the above illustration, following are the important points to be considered.
Index starts with 0.
Array length is 10 which means it can store 10 elements.
Each element can be accessed via its index. For example, we can fetch an element at index 6 as 9.
RASHID HUSAIN
Basic Operations
Traverse Operation
1
Example
Following program traverses and prints the elements of an array:
#include <stdio.h>
main() {
int LA[] = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;
printf("The original array elements are :\n");
for(i = 0; i<n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
}
When we compile and execute the above program, it produces the following result −
Output
The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
RASHID HUSAIN
Insertion Operation
Insert operation is to insert one or more data elements into an array. Based on the requirement, a new element
can be added at the beginning, end, or any given index of array.
Algorithm:
INSERT (A, n, k, data)
1. Set i = n-1
2. Repeat steps 3 & 4 while i >= k-1
3. Set A[i+1] = A[i]
4. Set i = i-1
5. Set A[k-1] = data
6. Set n = n+1
7. Exit
Deletion Operation
Deletion refers to removing an existing element from the array and re-organizing all elements of an array.
Algorithm:
DELETE (A, n, k, data)
2
1. Set data = A[k-1]
2. Repeat for(i = k-1; i < n; i++)
3. Set A[i] = A[i+1]
4. Set n = n-1
5. Exit
SEARCHING TECHNIQUES
Linear Search
Linear search is a very simple search algorithm. In this type of search, a sequential search is made over all items
one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the
search continues till the end of the data collection.
Algorithm:
LSEARCH(A, n, item)
1. Loc = -1
2. i=1
3. Repeat while i<=n and A[i] ≠ item
RASHID HUSAIN
i = i+1
Loc = i
5. Return Loc
Binary Search
Binary search is a fast search algorithm with run-time complexity of Ο(log n). This search algorithm works on
the principle of divide and conquer. For this algorithm to work properly, the data collection should be in the
sorted form.
Binary search looks for a particular item by comparing the middle most item of the collection. If a match
occurs, then the index of item is returned. If the middle item is greater than the item, then the item is searched in
the sub-array to the left of the middle item. Otherwise, the item is searched for in the sub-array to the right of
the middle item. This process continues on the sub-array as well until the size of the subarray reduces to zero.
Algorithm:
BSEARCH(A, n, item)
3
1. Loc = -1
2. B = 1, E = N
3. while B <= E
mid = | (B+E)/2 |
B = mid + 1
else
E = mid - 1
4. Return Loc
Sorting refers to arranging data in a particular format. Sorting algorithm specifies the way to arrange data in a
particular order. Most common orders are in numerical or lexicographical order.
The importance of sorting lies in the fact that data searching can be optimized to a very high level, if data is
stored in a sorted manner. Sorting is also used to represent data in more readable formats. Following are some
of the examples of sorting in real-life scenarios −
Telephone Directory − The telephone directory stores the telephone numbers of people sorted
by their names, so that the names can be searched easily.
Dictionary − The dictionary stores words in an alphabetical order so that searching of any word
becomes easy.
Sorting algorithms may require some extra space for comparison and temporary storage of few data elements.
These algorithms do not require any extra space and sorting is said to happen in-place, or for example, within
the array itself. This is called in-place sorting. Bubble sort is an example of in-place sorting.
However, in some sorting algorithms, the program requires space which is more than or equal to the elements
being sorted. Sorting which uses equal or more space is called not-in-place sorting. Merge-sort is an example
of not-in-place sorting.
4
STABLE AND NOT STABLE SORTING
If a sorting algorithm, after sorting the contents, does not change the sequence of similar content in which they
appear, it is called stable sorting.
If a sorting algorithm, after sorting the contents, changes the sequence of similar content in which they appear,
it is called unstable sorting.
Stability of an algorithm matters when we wish to maintain the sequence of original elements, like in a tuple for
example.
RASHID HUSAIN
A sorting algorithm is said to be adaptive, if it takes advantage of already 'sorted' elements in the list that is to
be sorted. That is, while sorting if the source list has some element already sorted, adaptive algorithms will take
this into account and will try not to re-order them.
A non-adaptive algorithm is one which does not take into account the elements which are already sorted. They
try to force every single element to be re-ordered to confirm their sortedness.
IMPORTANT TERMS
Some terms are generally coined while discussing sorting techniques, here is a brief introduction to them −
Increasing Order
A sequence of values is said to be in increasing order, if the successive element is greater than the previous
one. For example, 1, 3, 4, 6, 8, 9 are in increasing order, as every next element is greater than the previous
element.
Decreasing Order
A sequence of values is said to be in decreasing order, if the successive element is less than the current one.
For example, 9, 8, 6, 4, 3, 1 are in decreasing order, as every next element is less than the previous element.
5
Non-Increasing Order
A sequence of values is said to be in non-increasing order, if the successive element is less than or equal to its
previous element in the sequence. This order occurs when the sequence contains duplicate values. For example,
9, 8, 6, 3, 3, 1 are in non-increasing order, as every next element is less than or equal to (in case of 3) but not
greater than any previous element.
Non-Decreasing Order
A sequence of values is said to be in non-decreasing order, if the successive element is greater than or equal to
its previous element in the sequence. This order occurs when the sequence contains duplicate values. For
example, 1, 3, 3, 6, 8, 9 are in non-decreasing order, as every next element is greater than or equal to (in case of
3) but not less than the previous one.
BUBBLE SORT
Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based algorithm in which each
pair of adjacent elements is compared and the elements are swapped if they are not in order. This algorithm is
not suitable for large data sets as its average and worst case complexity are of Ο(n 2) where n is the number of
items.
We take an unsorted array for our example. Bubble sort takes Ο(n2) time so we're keeping it short and precise.
RASHID HUSAIN
Bubble sort starts with very first two elements, comparing them to check which one is greater.
In this case, value 33 is greater than 14, so it is already in sorted locations. Next, we compare 33 with 27.
We find that 27 is smaller than 33 and these two values must be swapped.
6
Next we compare 33 and 35. We find that both are in already sorted positions.
We know then that 10 is smaller 35. Hence they are not sorted.
We swap these values. We find that we have reached the end of the array. After one iteration, the array should
look like this −
RASHID HUSAIN
To be precise, we are now showing how an array should look like after each iteration. After the second iteration,
it should look like this −
Notice that after each iteration, at least one value moves at the end.
And when there's no swap required, bubble sorts learns that an array is completely sorted.
Algorithm
7
We assume list is an array of n elements. We further assume that swap function swaps the values of the given
array elements.
begin BubbleSort(list)
return list
end BubbleSort
MERGE SORT
Merge sort is a sorting technique based on divide and conquer technique. With worst-case time complexity
being Ο(n log n), it is one of the most respected algorithms.
Merge sort first divides the array into equal halves and then combines them in a sorted manner.
We know that merge sort first divides the whole array iteratively into equal halves unless the atomic values are
achieved. We see here that an array of 8 items is divided into two arrays of size 4.
This does not change the sequence of appearance of items in the original. Now we divide these two arrays into
halves.
We further divide these arrays and we achieve atomic value which can no more be divided.
8
Now, we combine them in exactly the same manner as they were broken down. Please note the color codes
given to these lists.
We first compare the element for each list and then combine them into another list in a sorted manner. We see
that 14 and 33 are in sorted positions. We compare 27 and 10 and in the target list of 2 values we put 10 first,
followed by 27. We change the order of 19 and 35 whereas 42 and 44 are placed sequentially.
In the next iteration of the combining phase, we compare lists of two data values, and merge them into a list of
found data values placing all in a sorted order.
After the final merging, the list should look like this −
Algorithm
Merge sort keeps on dividing the list into equal halves until it can no more be divided. By definition, if it is only
one element in the list, it is sorted. Then, merge sort combines the smaller sorted lists keeping the new list
sorted too.
Step 1 − if it is only one element in the list it is already sorted, return.
Step 2 − divide the list recursively into two halves until it can no more be divided.
Step 3 − merge the smaller lists into new list in sorted order.
Pseudocode
MERGE-SORT (A, p, r)
1. IF p < r
2. q = | (p + q)/2|
3. MERGE – SORT (A, p, q)
4. MERGE – SORT (A, q + 1, r)
5. MERGE (A, p, q, r)
MERGE (A, p, q, r)
1. n1 q–p+1
9
2. n2 r–q
3. Create array L[1….n1 +1] and R[1……n2+1]
4. for i to n1
5. do L[i] A[p+ i-1]
6. for j 1 to n2
7. do R[j] A[q+j]
8. L[n1 + 1] ∞
9. R[n2 + 1] ∞
10. i 1
11. j 1
12. for k p to r
13. do if L[i] R[j]
14. then A[k] L[j]
15. i ++
16. else A[k] R[j]
17. j ++
INSERTION SORT
This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which is always sorted.
For example, the lower part of an array is maintained to be sorted. An element which is to be 'insert'ed in this
sorted sub-list, has to find its appropriate place and then it has to be inserted there. Hence the name, insertion
sort.
The array is searched sequentially and unsorted items are moved and inserted into the sorted sub-list (in the
RASHID HUSAIN
same array). This algorithm is not suitable for large data sets as its average and worst case complexity are of
Ο(n2), where n is the number of items.
It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted sub-list.
It swaps 33 with 27. It also checks with all the elements of sorted sub-list. Here we see that the sorted sub-list
has only one element 14, and 27 is greater than 14. Hence, the sorted sub-list remains sorted after swapping.
By now we have 14 and 27 in the sorted sub-list. Next, it compares 33 with 10.
RASHID HUSAIN
So we swap them.
11
We swap them again. By the end of third iteration, we have a sorted sub-list of 4 items.
This process goes on until all the unsorted values are covered in a sorted sub-list. Now we shall see some
programming aspects of insertion sort.
Pseudocode
INSERTION-SORT (A)
1. for j = 2 to A.length
2. Key = A[j]
3. // Insert A[j] into the sorted sequence A[1….j-1]
4. i=j–1
5. while i > 0 and A[i] > key
6. A[i +1] = A[i]
7. i=i–1
8. A[i + 1] = key
QUICK SORT
RASHID HUSAIN
Quick sort algorithm is one of the most widely used sorting algorithms. It follows a divide and conquer
paradigm. We usually use Recursion in quicksort implementation. In each recursive call, a pivot is chosen, then
the array is partitioned in such a way that all the elements less than pivot lie to the left and all the elements
greater than pivot lie to the right.
After every call, the chosen pivot occupies its correct position in the array which it is supposed to as in a sorted
array. So with each step, our problem gets reduced by 2 which leads to quick sorting. Pivot can be an element.
Example: last element of the current array or the first element of current array or random pivot etc.
Based on our understanding of partitioning in quick sort, we will now try to write an algorithm for it, which is
as follows.
Step 1 − Choose the highest index value has pivot
Step 2 − Take two variables to point left and right of the list excluding pivot
Step 3 − left points to the low index
Step 4 − right points to the high
Step 5 − while value at left is less than pivot move right
Step 6 − while value at right is greater than pivot move left
Step 7 − if both step 5 and step 6 does not match swap left and right
12
Step 8 − if left ≥ right, the point where they met is new pivot
RASHID HUSAIN
13