SlideShare a Scribd company logo
1 of 70
Download to read offline
Sunawar Khan Ahsan
MS(CS)
IIUI
ARRAYS
ARRAYS & Matrices
SK Ahsan
WHAT IS ARRAYS?
 An array is a group of consecutive memory locations
with same name and data type.
 Simple variable is a single memory location with
unique name and a type. But an Array is collection of
different adjacent memory locations. All these
memory locations have one collective name and type.
 The memory locations in the array are known as
elements of array. The total number of elements in the
array is called length.
 The elements of array is accessed with reference to
its position in array, that is call index or subscript.
ARRAYS & Matrices
SK Ahsan
WHAT IS AN ARRAY?
■ We refer to all stored values in an array by its
name
■ If we would like to access a particular value
stored in an array, we specify its index (i.e. its
position relative to the first array value)
– The first array index is always 0
– The second value is stored in index 1
– Etc.
ARRAYS & Matrices
SK Ahsan
WHAT IS AN ARRAYS?
■ Arrays
– Structures of related data items
– Static entity (same size throughout
program)
■ A few types
– Pointer-based arrays (C-like)
– Arrays as objects (C++)
ARRAYS & Matrices
SK Ahsan
What is an Array
■ We are interested in one-dimensional arrays
■ An array has a fixed number of elements and all
elements are of the same type
■ Each box has an index which in java and C++ starts
with 0
■ Here is an array which holds the ages of 10 people
0 1 2 3 4 5 6 7 8 9
32 34 56 32 12 67 21 34 21 45
ARRAYS & Matrices
SK Ahsan
Examples of Arrays
■ Draw an array of 20 elements which contains
student marks – what type will it be ?
■ Draw an array of 15 elements which contains
student grades ranging form A-E – what type
will it be?
ARRAYS & Matrices
SK Ahsan
Advantages / Uses of Arrays
■ Arrays can store a large number of value with single name.
■ Arrays are used to process many value easily and quickly.
■ The values stored in an array can be sorted easily.
■ The search process can be applied on arrays easily.
ARRAYS & Matrices
SK Ahsan
Types of Arrays:
–One-Dimensional Array
–Two-Dimensional Array
–N-Dimensional Array
ARRAYS & Matrices
SK Ahsan
One-D Array
A type of array in which all elements are arranged in the form of a list is known as 1-D array or
single dimensional array or linear list.
Declaring 1-D Array:
data_type identifier[length]; e.g: int marks[5];
o Data _type: Data type of values to be stored in the array.
o Identifier: Name of the array.
o Length: Number of elements.
ARRAYS & Matrices
SK Ahsan
ARRAY INITIALIZATION
■ Initializing arrays
– For loop
■ Set each element
– Initializer list
■ Specify each element when array declared
int n[ 5 ] = { 1, 2, 3, 4, 5 };
■ If not enough initializers, rightmost elements 0
■ If too many syntax error
– To set every element to same value
int n[ 5 ] = { 0 };
– If array size omitted, initializers determine size
int n[] = { 1, 2, 3, 4, 5 };
■ 5 initializers, therefore 5 element array
ARRAYS & Matrices
SK Ahsan
One-D array Intialization
The process of assigning values to array elements at the time of array declaration is called array
initialization.
Syntax:
data_type identifier[length]={ List of values }; e.g: int marks[5]={70,54,82,96,49};
o Data _type: Data type of values to be stored in the array.
o Identifier: Name of the array.
o Length: Number of elements
o List of values: Values to initialize the array. Initializing values must be constant
70 54 82 96 49
ARRAYS & Matrices
SK Ahsan
Accessing element of array
■ Individual Element:
Array_name[index];
■ Using Loop:
int marks[5];
for(int i=0;i<=4;i++)
marks[i]=i;
ARRAYS & Matrices
SK Ahsan
INITIALIZE AND ACCESS INDIVIDUAL INDEX
// This program displays the number of days in each month.
// It uses a 12-element int array.
#include <iostream.h>
void main(void)
{
int days[12];
days[0] = 31; // January
days[1] = 28; // February
days[2] = 31; // March
days[3] = 30; // April
days[4] = 31; // May
days[5] = 30; // June
days[6] = 31; // July
ARRAYS & Matrices
SK Ahsan
Cont…
days[7] = 31; // August
days[8] = 30; // September
days[9] = 31; // October
days[10] = 30; // November
days[11] = 31; // December
for (int count = 0; count < 12; count++)
{
cout << "Month " << (count + 1) << " has ";
cout << days[count] << " days.n";
}
}
ARRAYS & Matrices
SK Ahsan
Output
Month 1 has 31 days.
Month 2 has 28 days.
Month 3 has 31 days.
Month 4 has 30 days.
Month 5 has 31 days.
Month 6 has 30 days.
Month 7 has 31 days.
Month 8 has 31 days.
Month 9 has 30 days.
Month 10 has 31 days.
Month 11 has 30 days.
Month 12 has 31 days.
ARRAYS & Matrices
SK Ahsan
PARTIAL ARRAY INITIALIZATION
// This program displays the number of days in each month.
// It uses a 12-element int array.
#include <iostream.h>
void main(void)
{
int days[12] = {31, 28, 31, 30,
31, 30, 31, 31,
30, 31, 30, 31};
for (int count = 0; count < 12; count++)
{
cout << "Month " << (count + 1) << " has ";
cout << days[count] << " days.n";
}
}
ARRAYS & Matrices
SK Ahsan
OUTPUT
Month 1 has 31 days.
Month 2 has 28 days.
Month 3 has 31 days.
Month 4 has 30 days.
Month 5 has 31 days.
Month 6 has 30 days.
Month 7 has 31 days.
Month 8 has 31 days.
Month 9 has 30 days.
Month 10 has 31 days.
Month 11 has 30 days.
Month 12 has 31 days.
ARRAYS & Matrices
SK Ahsan
Print ASCII Values
// This program uses an array of ten characters to store the
// first ten letters of the alphabet. The ASCII codes of the
// characters are displayed.
#include <iostream.h>
void main(void)
{
char letters[10] = {'A', 'B', 'C', 'D', 'E',
'F', 'G', 'H', 'I', 'J'};
cout << "Character" << "t" << "ASCII Coden";
cout << "--------" << "t" << "----------n";
for (int count = 0; count < 10; count++)
{
cout << letters[count] << "tt";
cout << int(letters[count]) << endl;
}
}
ARRAYS & Matrices
SK Ahsan
Output
Character ASCII Code
--------- ----------
A 65
B 66
C 67
D 68
E 69
F 70
G 71
H 72
I 73
J 74
ARRAYS & Matrices
SK Ahsan
// Histogram printing program.
#include <iostream>
#include <iomanip>
using std::setw;
int main() {
const int arraySize = 10;
int n[ arraySize ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };
cout << "Element" << setw( 13 ) << "Value"<< setw( 17 ) << "Histogram"<< endl;
// for each element of array n, output a bar in histogram
for ( int i = 0; i < arraySize; i++ ) {
cout << setw( 7 ) << i << setw( 13 )<< n[ i ] << setw( 9 );
for ( int j = 0; j < n[ i ]; j++ ) // print one bar
cout << '*';
cout << endl; // start next line of output
} // end outer for structure
return 0; // indicates successful termination
} // end main
PRINT HISTOGRAM
Element Value Histogram
0 19 *******************
1 3 ***
2 15 ***************
3 7 *******
4 11 ***********
5 9 *********
6 13 *************
7 5 *****
8 17 *****************
9 1 *
ARRAYS & Matrices
SK Ahsan
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
float a[] = { 22.2,44.4, 66.6 };
float x=11.1;
cout << "I m going to Crash " << endl;
cin >> x;
a[3333] = 88.8; // ERROR: index is out of bounds!
system("PAUSE"); return 0;
}
ARRAY OUT OF BOUND
ARRAYS & Matrices
SK Ahsan
Accumulating the elements of array
■ You may need to sum the elements of an
array
■ Initialise the sum variable which contains the
total to zero
■ The instruction Sum = Sum + A(R ) tells the
computer to add the valve of element A(R ) to
the old valve of the sum (Sum) and to store
the result into sum memory location (Sum)
■ Algorithm
■ Loop : R = 1 to 10
■ sum = Sum + A( R)
■ Loop end
■ The number of elements in array is 10
■ The counter of loop (R ) allows the computer
to increase the element number by 1 each
time a piece of data is entered into a memory
location
■ Sum = Sum of the elements of A
■ A(R ) = element R in the A array
R
1 5
1
Sum = Sum +
A(R )
R
B
Calc
ARRAYS & Matrices
SK Ahsan
Searching In Array
Searching is a process of finding the required
data in the array. Searching becomes more
important when the length of the array is very
large.
There are two techniques to searching
elements in array as follows:
■ Sequential search
■ Binary search
ARRAYS & Matrices
SK Ahsan
Why Search ?
■ Everyday life -We always Looking for something – builder yellow
pages, universities, hairdressers
■ Computers can search
■ World wide web –
■ Spreadsheet –
■ Databases –
■ Large records – 1000s takes time - many comparison slow
system – user wont wait long time
ARRAYS & Matrices
SK Ahsan
Search Algorithms
■ Different types
– Sequential Search
– Binary Search
■ Discuss - search algorithms - analyze them
■ Analysis of the algorithms enables
programmers to decide which algorithm to use
for a specific application
ARRAYS & Matrices
SK Ahsan
Some observations – Key
■ Each item in a data set - special member that
uniquely identifies the item in the data set
■ For e.g University - a data set which contains
student records – student ID uniquely identifies
each student
■ This unique member of the item is called Key of
the item
ARRAYS & Matrices
SK Ahsan
Some observations - Key
■ Where can Keys of the item in a data set be used in ?
■ When searching the data set - for a particular item,
what do we do ?
■ compare the key of the item for which we are searching -
with the keys of the items in the data set – e.g if we
looking particular student id in a list of student id exam
results
ARRAYS & Matrices
SK Ahsan
Analysis of Algorithms
■ In addition to describing the algorithms – analyse
them
■ What does analysis of algorithms involve ?
- key comparisons
- Moreover – the number of key comparisons refers
to - the number of times the key of the item (in
search & sort algorithms) is compared with the
keys of the items in the list
ARRAYS & Matrices
SK Ahsan
Sequential search
■ Problem :-
– we want to search for a given element in a list.
■ Do we know where the target element occurs?.
ARRAYS & Matrices
SK Ahsan
Sequential Search
Sequential search is also known as linear or serial search. It follows
the following step to search a value in array.
– Visit the first element of array and compare its value with
required value.
– If the value of array matches with the desired value, the
search is complete.
– If the value of array does not match, move to next element an
repeat same process.
ARRAYS & Matrices
SK Ahsan
10 20 30 40 50 60 70 80 90 100
1 2 3 4 5 6 7 8 9 10
• Visit the first element of array and compare its value with
required value.
• If the value of array matches with the desired value, the search
is complete.
• If the value of array does not match, move to next element an
repeat same process.
ARRAYS & Matrices
SK Ahsan
• Visit the first element of array and compare its value with
required value.
• If the value of array matches with the desired value, the search
is complete.
• If the value of array does not match, move to next element an
repeat same process.
arr[1],10 = = 50
10 20 30 40 50 60 70 80 90 100
1 2 3 4 5 6 7 8 9 10
ARRAYS & Matrices
SK Ahsan
• Visit the first element of array and compare its value with
required value.
• If the value of array matches with the desired value, the search
is complete.
• If the value of array does not match, move to next element an
repeat same process.
arr[2],20 = = 50
10 20 30 40 50 60 70 80 90 100
1 2 3 4 5 6 7 8 9 10
ARRAYS & Matrices
SK Ahsan
• Visit the first element of array and compare its value with
required value.
• If the value of array matches with the desired value, the search
is complete.
• If the value of array does not match, move to next element an
repeat same process.
arr[3],30 = = 50
10 20 30 40 50 60 70 80 90 100
1 2 3 4 5 6 7 8 9 10
ARRAYS & Matrices
SK Ahsan
• Visit the first element of array and compare its value with
required value.
• If the value of array matches with the desired value, the search
is complete.
• If the value of array does not match, move to next element an
repeat same process.
arr[4],40 = = 50
10 20 30 40 50 60 70 80 90 100
1 2 3 4 5 6 7 8 9 10
ARRAYS & Matrices
SK Ahsan
• Visit the first element of array and compare its value with
required value.
• If the value of array matches with the desired value, the search
is complete.
• If the value of array does not match, move to next element an
repeat same process.
loc = i
loc = 5
arr[5],50 = = 50
Example Code 1
10 20 30 40 50 60 70 80 90 100
1 2 3 4 5 6 7 8 9 10
ARRAYS & Matrices
SK Ahsan
Binary Search
Binary search is a quicker method of searching for value in the array. Binary search is very quick
but it can only search an sorted array. It cannot be applied on an unsorted array.
o It locates the middle element of array and compare with desired number.
o If they are equal, search is successful and the index of middle element is returned.
o If they are not equal, it reduces the search to half of the array.
o If the search number is less than the middle element, it searches the first half of array.
Otherwise it searches the second half of the array. The process continues until the required
number is found or loop completes without successful search.
ARRAYS & Matrices
SK Ahsan
Binary Search
ARRAYS & Matrices
SK Ahsan
Binary Search: middle element
left + right
2
mid =
ARRAYS & Matrices
SK Ahsan
Binary Searchbool BinSearch(double list[ ], int n, double item, int&index){
int left=0;
int right=n-1;
int mid;
while(left<=right){
mid=(left+right)/2;
if(item> list [mid]){
left=mid+1; }
else if(item< list [mid]){
right=mid-1;}
else{
item= list [mid];
index=mid;
return true; }
}// while
return false;
}
ARRAYS & Matrices
SK Ahsan
Binary Search: Example
Example Code 1
ARRAYS & Matrices
SK Ahsan
Sorting Arrays
Sorting is a process of arranging the value of array in a particular order. An array can be
sorted in two order.
o Ascending Order
o Descending Order
12 25 33 37 48
48 37 33 25 12
ARRAYS & Matrices
SK Ahsan
Techniques Of Sorting Array
There are two techniques of sorting array:
o Selection Sort
o Bubble Sort
ARRAYS & Matrices
SK Ahsan
Bubble Sort
Bubble Sort is also known as exchange sort. It repeatedly visits the array and compares two
items at a time. It works as follows:
o Compare adjacent element. If the first is greater than the second, swap them.
o Repeat this for each pair of adjacent element, starting with the first two and
ending with the last two. (at this point last element should be greatest).
o Repeat the step for all elements except the last one.
o Keep repeating for one fewer element each time until there are no pairs to
compare.
ARRAYS & Matrices
SK Ahsan
Bubble sort
 Compare each element (except the last one) with its
neighbor to the right
 If they are out of order, swap them
 This puts the largest element at the very end
 The last element is now in the correct and final place
 Compare each element (except the last two) with its
neighbor to the right
 If they are out of order, swap them
 This puts the second largest element next to last
 The last two elements are now in their correct and final places
 Compare each element (except the last three) with its
neighbor to the right
 Continue as above until you have no unsorted elements on the
left
ARRAYS & Matrices
SK Ahsan
Example of bubble sort
7 2 8 5 4
2 7 8 5 4
2 7 8 5 4
2 7 5 8 4
2 7 5 4 8
2 7 5 4 8
2 5 7 4 8
2 5 4 7 8
2 7 5 4 8
2 5 4 7 8
2 4 5 7 8
2 5 4 7 8
2 4 5 7 8
2 4 5 7 8
(done)
ARRAYS & Matrices
SK Ahsan
Analysis of bubble sort
■ Let n = a.length = size of the array
■ The outer loop is executed n-1 times (call it n, that’s close enough)
■ Each time the outer loop is executed, the inner loop is executed
– Inner loop executes n-1 times at first, linearly dropping to just
once
– On average, inner loop executes about n/2 times for each
execution of the outer loop
– In the inner loop, the comparison is always done (constant
time), the swap might be done (also constant time)
■ Result is n * n/2 * k, that is, O(n2/2 + k) = O(n2)
ARRAYS & Matrices
SK Ahsan
Selection sort
■ Given an array of length n,
– Search elements 0 through n-1 and select the smallest
■ Swap it with the element in location 0
– Search elements 1 through n-1 and select the smallest
■ Swap it with the element in location 1
– Search elements 2 through n-1 and select the smallest
■ Swap it with the element in location 2
– Search elements 3 through n-1 and select the smallest
■ Swap it with the element in location 3
– Continue in this fashion until there’s nothing left to search
ARRAYS & Matrices
SK Ahsan
Selection Sort
Selection sort is a technique that sort an array. It selects an element in the array and moves
it to its proper position. Selection sort works as follows:
1. Find the minimum value in the list.
2. Swap it with value in the first position.
3. Sort the remainder of the list excluding the first value.
ARRAYS & Matrices
SK Ahsan
Example and analysis of selection sort
 The selection sort might swap an array element
with itself--this is harmless, and not worth
checking for
 Analysis:
 The outer loop executes n-1 times
 The inner loop executes about n/2 times on
average (from n to 2 times)
 Work done in the inner loop is constant
(swap two array elements)
 Time required is roughly (n-1)*(n/2)
 You should recognize this as O(n2)
7 2 8 5 4
2 7 8 5 4
2 4 8 5 7
2 4 5 8 7
2 4 5 7 8
SORTING
TECHNIQUES
ARRAYS & Matrices
SK Ahsan
Selection Sort
■ Algorithm
– Step 1 − Set MIN to location 0
– Step 2 − Search the minimum element in the list
– Step 3 − Swap with value at location MIN
– Step 4 − Increment MIN to point to next element
– Step 5 − Repeat until list is sorted
ARRAYS & Matrices
SK Ahsan
Selection sort
■ Pseudo code
– procedure selection sort
– list : array of items
– n : size of list
– for i = 1 to n - 1
– /* set current element as minimum*/
– min = i ;
– /* check the element to be minimum */
– for j = i+1 to n
– if list[j] < list[min] then
– min = j ;
– end if
– end for
– /* swap the minimum element with the
current element*/
– if index Min != i then
– swap list[min] and list[i]
– end if
– end for
– end procedure EXAMPLE CODE 1
EXAMPLE CODE 2
ARRAYS & Matrices
SK Ahsan
DRY RUN
■ Iteration 1
PASS 1
0 1 2 3 4
56 78 33 81 12
ARRAYS & Matrices
SK Ahsan
DRY RUN
■ Iteration 2
PASS 1
0 1 2 3 4
56 78 33 81 12
ARRAYS & Matrices
SK Ahsan
DRY RUN
■ Iteration 3
PASS 1
0 1 2 3 4
56 78 33 81 12
ARRAYS & Matrices
SK Ahsan
DRY RUN
■ Iteration 4
PASS 1
0 1 2 3 4
56 78 33 81 12
12 78 33 81 56
ARRAYS & Matrices
SK Ahsan
DRY RUN
■ Iteration 1
PASS 2
0 1 2 3 4
12 78 33 81 56
ARRAYS & Matrices
SK Ahsan
DRY RUN
■ Iteration 2
PASS 2
0 1 2 3 4
12 78 33 81 56
ARRAYS & Matrices
SK Ahsan
DRY RUN
■ Iteration 3
PASS 2
0 1 2 3 4
12 78 33 81 56
12 33 78 81 56
ARRAYS & Matrices
SK Ahsan
DRY RUN
■ Iteration 1
PASS 3
0 1 2 3 4
12 33 78 81 56
ARRAYS & Matrices
SK Ahsan
DRY RUN
■ Iteration 2
PASS 3
0 1 2 3 4
12 33 78 81 56
12 33 56 81 78
ARRAYS & Matrices
SK Ahsan
DRY RUN
■ Iteration 1
PASS 4
0 1 2 3 4
12 33 56 81 78
12 33 56 78 81
ARRAYS & Matrices
SK Ahsan
Bubble sort■ Algorithm
– begin BubbleSort(list)
– for all elements of list
– if list[i] > list[i+1]
– swap(list[i], list[i+1])
– end if
– end for
–
– return list
– end BubbleSort
ARRAYS & Matrices
SK Ahsan
Bubble sort
■ Pseudo code
– procedure bubbleSort( list : array of items )
– loop = list.count
– for i = 0 to loop-1 do:
– swapped = false
– for j = 0 to loop-1 do:
– /* compare the adjacent elements */
– if list[j] > list[j+1] then
– /* swap them */
– swap( list[j], list[j+1] )
– swapped = true
– end if
– end for
– /*if no number was swapped that means array is sorted now, break the
loop.*/
– if(not swapped) then
– break
– end if
– end for
– end procedure return list
ARRAYS & Matrices
SK Ahsan
Two-D Arrays
Two-D array can be considered as table that consists of rows and columns. Each element in 2-D
array is refered with the help of two indexes. One index indicates row and second indicates the
column.
Declaring 2-D Array:
Data_type Identifier[row][column]; e.g:
int arr[4][3];
o Data _type: Data type of values to be stored in the array.
o Identifier: Name of the array.
o Rows : # of Rows in the table of array.
o Column : # of Columns in the table of array.
0,0 0,1 0,2
1,0 1,1 1,2
2,0 2,1 2,2
3,0 3,1 3,2
ARRAYS & Matrices
SK Ahsan
Two-D array Intialization
The two-D array can also be initialized at the time of declaration. Initialization is performed by
assigning the initial values in braces seperated by commas.
Some important points :
o The elements of each row are enclosed within braces and seperated by comma.
o All rows are enclosed within braces.
o For number arrays, if all elements are not specified , the un specified elements are
initialized by zero.
ARRAYS & Matrices
SK Ahsan
Two-D array Intialization
Syntax:
int arr[4][3]={ {12,5,22},
{95,3,41},
{77,6,53},
{84,59,62} }
12 5 22
95 3 41
77 6 53
84 59 62
Column indexes
Row indexes
0
2
1
3
10 2
ARRAYS & Matrices
SK Ahsan
Case Study: Computing Mean, Median and
Mode Using Arrays
■ Mean
– Average (sum/number of elements)
■ Median
– Number in middle of sorted list
– 1, 2, 3, 4, 5 (3 is median)
– If even number of elements, take average of middle two
■ Mode
– Number that occurs most often
– 1, 1, 1, 2, 3, 3, 4, 5 (1 is mode)
ARRAYS & Matrices
SK Ahsan
Case Study
■Find Set Properties
–Set Union
–Set Differences

More Related Content

What's hot

Javascript ADT - List
Javascript   ADT - ListJavascript   ADT - List
Javascript ADT - ListSamuel Santos
 
Unit 2 linear data structures
Unit 2   linear data structuresUnit 2   linear data structures
Unit 2 linear data structuresSenthil Murugan
 
Hash table
Hash tableHash table
Hash tableVu Tran
 
BCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHI
BCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHIBCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHI
BCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHISowmya Jyothi
 
BCA DATA STRUCTURES INTRODUCTION AND OVERVIEW SOWMYA JYOTHI
BCA DATA STRUCTURES INTRODUCTION AND OVERVIEW SOWMYA JYOTHIBCA DATA STRUCTURES INTRODUCTION AND OVERVIEW SOWMYA JYOTHI
BCA DATA STRUCTURES INTRODUCTION AND OVERVIEW SOWMYA JYOTHISowmya Jyothi
 
Array linear data_structure_2 (1)
Array linear data_structure_2 (1)Array linear data_structure_2 (1)
Array linear data_structure_2 (1)eShikshak
 
Arrays Data Structure
Arrays Data StructureArrays Data Structure
Arrays Data Structurestudent
 
Array operations
Array operationsArray operations
Array operationsZAFAR444
 
Introduction to data_structure
Introduction to data_structureIntroduction to data_structure
Introduction to data_structureAshim Lamichhane
 
R DATA STRUCTURES 1
R DATA STRUCTURES 1R DATA STRUCTURES 1
R DATA STRUCTURES 1Milind M
 
Introduction to data structure
Introduction to data structureIntroduction to data structure
Introduction to data structureVivek Kumar Sinha
 

What's hot (20)

Data structures2
Data structures2Data structures2
Data structures2
 
Array
ArrayArray
Array
 
Array
ArrayArray
Array
 
Javascript ADT - List
Javascript   ADT - ListJavascript   ADT - List
Javascript ADT - List
 
Unit 2 linear data structures
Unit 2   linear data structuresUnit 2   linear data structures
Unit 2 linear data structures
 
Array
ArrayArray
Array
 
Data structures
Data structuresData structures
Data structures
 
Hash table
Hash tableHash table
Hash table
 
Data structures
Data structuresData structures
Data structures
 
Java Regular Expression PART I
Java Regular Expression PART IJava Regular Expression PART I
Java Regular Expression PART I
 
BCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHI
BCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHIBCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHI
BCA DATA STRUCTURES SEARCHING AND SORTING MRS.SOWMYA JYOTHI
 
BCA DATA STRUCTURES INTRODUCTION AND OVERVIEW SOWMYA JYOTHI
BCA DATA STRUCTURES INTRODUCTION AND OVERVIEW SOWMYA JYOTHIBCA DATA STRUCTURES INTRODUCTION AND OVERVIEW SOWMYA JYOTHI
BCA DATA STRUCTURES INTRODUCTION AND OVERVIEW SOWMYA JYOTHI
 
Array linear data_structure_2 (1)
Array linear data_structure_2 (1)Array linear data_structure_2 (1)
Array linear data_structure_2 (1)
 
Arrays Data Structure
Arrays Data StructureArrays Data Structure
Arrays Data Structure
 
Array operations
Array operationsArray operations
Array operations
 
Introduction to data_structure
Introduction to data_structureIntroduction to data_structure
Introduction to data_structure
 
arrays
arraysarrays
arrays
 
Presentation of array
Presentation of arrayPresentation of array
Presentation of array
 
R DATA STRUCTURES 1
R DATA STRUCTURES 1R DATA STRUCTURES 1
R DATA STRUCTURES 1
 
Introduction to data structure
Introduction to data structureIntroduction to data structure
Introduction to data structure
 

Similar to Arrays (20)

Arrays
ArraysArrays
Arrays
 
Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
 
Data structure.pptx
Data structure.pptxData structure.pptx
Data structure.pptx
 
Data structures and algorithms arrays
Data structures and algorithms   arraysData structures and algorithms   arrays
Data structures and algorithms arrays
 
Data structure ppt
Data structure pptData structure ppt
Data structure ppt
 
data structure unit -1_170434dd7400.pptx
data structure unit -1_170434dd7400.pptxdata structure unit -1_170434dd7400.pptx
data structure unit -1_170434dd7400.pptx
 
Array assignment
Array assignmentArray assignment
Array assignment
 
Arrays In C Language
Arrays In C LanguageArrays In C Language
Arrays In C Language
 
R programming slides
R  programming slidesR  programming slides
R programming slides
 
Arrays
ArraysArrays
Arrays
 
Arrays_in_c++.pptx
Arrays_in_c++.pptxArrays_in_c++.pptx
Arrays_in_c++.pptx
 
9 Arrays
9 Arrays9 Arrays
9 Arrays
 
21CS32 DS Module 1 PPT.pptx
21CS32 DS Module 1 PPT.pptx21CS32 DS Module 1 PPT.pptx
21CS32 DS Module 1 PPT.pptx
 
Arrays
ArraysArrays
Arrays
 
DSA - Array.pptx
DSA - Array.pptxDSA - Array.pptx
DSA - Array.pptx
 
arrayppt.pptx
arrayppt.pptxarrayppt.pptx
arrayppt.pptx
 
what is arrays in c language
what is arrays in c languagewhat is arrays in c language
what is arrays in c language
 
PPT Lecture 2.2.1 onn c++ data structures
PPT Lecture 2.2.1 onn c++ data structuresPPT Lecture 2.2.1 onn c++ data structures
PPT Lecture 2.2.1 onn c++ data structures
 
Arrays
ArraysArrays
Arrays
 
datastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptxdatastructureppt-190327174340 (1).pptx
datastructureppt-190327174340 (1).pptx
 

More from International Islamic University (20)

Hash tables
Hash tablesHash tables
Hash tables
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Graph 1
Graph 1Graph 1
Graph 1
 
Graph 2
Graph 2Graph 2
Graph 2
 
Graph 3
Graph 3Graph 3
Graph 3
 
Greedy algorithm
Greedy algorithmGreedy algorithm
Greedy algorithm
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Quick sort
Quick sortQuick sort
Quick sort
 
Merge sort
Merge sortMerge sort
Merge sort
 
Linear timesorting
Linear timesortingLinear timesorting
Linear timesorting
 
Facial Expression Recognitino
Facial Expression RecognitinoFacial Expression Recognitino
Facial Expression Recognitino
 
Lecture#4
Lecture#4Lecture#4
Lecture#4
 
Lecture#3
Lecture#3 Lecture#3
Lecture#3
 
Lecture#2
Lecture#2 Lecture#2
Lecture#2
 
Case study
Case studyCase study
Case study
 
Pcb
PcbPcb
Pcb
 
Data transmission
Data transmissionData transmission
Data transmission
 
Basic organization of computer
Basic organization of computerBasic organization of computer
Basic organization of computer
 
Sorting techniques
Sorting techniquesSorting techniques
Sorting techniques
 
Linear search-and-binary-search
Linear search-and-binary-searchLinear search-and-binary-search
Linear search-and-binary-search
 

Recently uploaded

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 

Recently uploaded (20)

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 

Arrays

  • 2. ARRAYS & Matrices SK Ahsan WHAT IS ARRAYS?  An array is a group of consecutive memory locations with same name and data type.  Simple variable is a single memory location with unique name and a type. But an Array is collection of different adjacent memory locations. All these memory locations have one collective name and type.  The memory locations in the array are known as elements of array. The total number of elements in the array is called length.  The elements of array is accessed with reference to its position in array, that is call index or subscript.
  • 3. ARRAYS & Matrices SK Ahsan WHAT IS AN ARRAY? ■ We refer to all stored values in an array by its name ■ If we would like to access a particular value stored in an array, we specify its index (i.e. its position relative to the first array value) – The first array index is always 0 – The second value is stored in index 1 – Etc.
  • 4. ARRAYS & Matrices SK Ahsan WHAT IS AN ARRAYS? ■ Arrays – Structures of related data items – Static entity (same size throughout program) ■ A few types – Pointer-based arrays (C-like) – Arrays as objects (C++)
  • 5. ARRAYS & Matrices SK Ahsan What is an Array ■ We are interested in one-dimensional arrays ■ An array has a fixed number of elements and all elements are of the same type ■ Each box has an index which in java and C++ starts with 0 ■ Here is an array which holds the ages of 10 people 0 1 2 3 4 5 6 7 8 9 32 34 56 32 12 67 21 34 21 45
  • 6. ARRAYS & Matrices SK Ahsan Examples of Arrays ■ Draw an array of 20 elements which contains student marks – what type will it be ? ■ Draw an array of 15 elements which contains student grades ranging form A-E – what type will it be?
  • 7. ARRAYS & Matrices SK Ahsan Advantages / Uses of Arrays ■ Arrays can store a large number of value with single name. ■ Arrays are used to process many value easily and quickly. ■ The values stored in an array can be sorted easily. ■ The search process can be applied on arrays easily.
  • 8. ARRAYS & Matrices SK Ahsan Types of Arrays: –One-Dimensional Array –Two-Dimensional Array –N-Dimensional Array
  • 9. ARRAYS & Matrices SK Ahsan One-D Array A type of array in which all elements are arranged in the form of a list is known as 1-D array or single dimensional array or linear list. Declaring 1-D Array: data_type identifier[length]; e.g: int marks[5]; o Data _type: Data type of values to be stored in the array. o Identifier: Name of the array. o Length: Number of elements.
  • 10. ARRAYS & Matrices SK Ahsan ARRAY INITIALIZATION ■ Initializing arrays – For loop ■ Set each element – Initializer list ■ Specify each element when array declared int n[ 5 ] = { 1, 2, 3, 4, 5 }; ■ If not enough initializers, rightmost elements 0 ■ If too many syntax error – To set every element to same value int n[ 5 ] = { 0 }; – If array size omitted, initializers determine size int n[] = { 1, 2, 3, 4, 5 }; ■ 5 initializers, therefore 5 element array
  • 11. ARRAYS & Matrices SK Ahsan One-D array Intialization The process of assigning values to array elements at the time of array declaration is called array initialization. Syntax: data_type identifier[length]={ List of values }; e.g: int marks[5]={70,54,82,96,49}; o Data _type: Data type of values to be stored in the array. o Identifier: Name of the array. o Length: Number of elements o List of values: Values to initialize the array. Initializing values must be constant 70 54 82 96 49
  • 12. ARRAYS & Matrices SK Ahsan Accessing element of array ■ Individual Element: Array_name[index]; ■ Using Loop: int marks[5]; for(int i=0;i<=4;i++) marks[i]=i;
  • 13. ARRAYS & Matrices SK Ahsan INITIALIZE AND ACCESS INDIVIDUAL INDEX // This program displays the number of days in each month. // It uses a 12-element int array. #include <iostream.h> void main(void) { int days[12]; days[0] = 31; // January days[1] = 28; // February days[2] = 31; // March days[3] = 30; // April days[4] = 31; // May days[5] = 30; // June days[6] = 31; // July
  • 14. ARRAYS & Matrices SK Ahsan Cont… days[7] = 31; // August days[8] = 30; // September days[9] = 31; // October days[10] = 30; // November days[11] = 31; // December for (int count = 0; count < 12; count++) { cout << "Month " << (count + 1) << " has "; cout << days[count] << " days.n"; } }
  • 15. ARRAYS & Matrices SK Ahsan Output Month 1 has 31 days. Month 2 has 28 days. Month 3 has 31 days. Month 4 has 30 days. Month 5 has 31 days. Month 6 has 30 days. Month 7 has 31 days. Month 8 has 31 days. Month 9 has 30 days. Month 10 has 31 days. Month 11 has 30 days. Month 12 has 31 days.
  • 16. ARRAYS & Matrices SK Ahsan PARTIAL ARRAY INITIALIZATION // This program displays the number of days in each month. // It uses a 12-element int array. #include <iostream.h> void main(void) { int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; for (int count = 0; count < 12; count++) { cout << "Month " << (count + 1) << " has "; cout << days[count] << " days.n"; } }
  • 17. ARRAYS & Matrices SK Ahsan OUTPUT Month 1 has 31 days. Month 2 has 28 days. Month 3 has 31 days. Month 4 has 30 days. Month 5 has 31 days. Month 6 has 30 days. Month 7 has 31 days. Month 8 has 31 days. Month 9 has 30 days. Month 10 has 31 days. Month 11 has 30 days. Month 12 has 31 days.
  • 18. ARRAYS & Matrices SK Ahsan Print ASCII Values // This program uses an array of ten characters to store the // first ten letters of the alphabet. The ASCII codes of the // characters are displayed. #include <iostream.h> void main(void) { char letters[10] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'}; cout << "Character" << "t" << "ASCII Coden"; cout << "--------" << "t" << "----------n"; for (int count = 0; count < 10; count++) { cout << letters[count] << "tt"; cout << int(letters[count]) << endl; } }
  • 19. ARRAYS & Matrices SK Ahsan Output Character ASCII Code --------- ---------- A 65 B 66 C 67 D 68 E 69 F 70 G 71 H 72 I 73 J 74
  • 20. ARRAYS & Matrices SK Ahsan // Histogram printing program. #include <iostream> #include <iomanip> using std::setw; int main() { const int arraySize = 10; int n[ arraySize ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; cout << "Element" << setw( 13 ) << "Value"<< setw( 17 ) << "Histogram"<< endl; // for each element of array n, output a bar in histogram for ( int i = 0; i < arraySize; i++ ) { cout << setw( 7 ) << i << setw( 13 )<< n[ i ] << setw( 9 ); for ( int j = 0; j < n[ i ]; j++ ) // print one bar cout << '*'; cout << endl; // start next line of output } // end outer for structure return 0; // indicates successful termination } // end main PRINT HISTOGRAM Element Value Histogram 0 19 ******************* 1 3 *** 2 15 *************** 3 7 ******* 4 11 *********** 5 9 ********* 6 13 ************* 7 5 ***** 8 17 ***************** 9 1 *
  • 21. ARRAYS & Matrices SK Ahsan #include <iostream> #include <stdlib.h> using namespace std; int main(){ float a[] = { 22.2,44.4, 66.6 }; float x=11.1; cout << "I m going to Crash " << endl; cin >> x; a[3333] = 88.8; // ERROR: index is out of bounds! system("PAUSE"); return 0; } ARRAY OUT OF BOUND
  • 22. ARRAYS & Matrices SK Ahsan Accumulating the elements of array ■ You may need to sum the elements of an array ■ Initialise the sum variable which contains the total to zero ■ The instruction Sum = Sum + A(R ) tells the computer to add the valve of element A(R ) to the old valve of the sum (Sum) and to store the result into sum memory location (Sum) ■ Algorithm ■ Loop : R = 1 to 10 ■ sum = Sum + A( R) ■ Loop end ■ The number of elements in array is 10 ■ The counter of loop (R ) allows the computer to increase the element number by 1 each time a piece of data is entered into a memory location ■ Sum = Sum of the elements of A ■ A(R ) = element R in the A array R 1 5 1 Sum = Sum + A(R ) R B Calc
  • 23. ARRAYS & Matrices SK Ahsan Searching In Array Searching is a process of finding the required data in the array. Searching becomes more important when the length of the array is very large. There are two techniques to searching elements in array as follows: ■ Sequential search ■ Binary search
  • 24. ARRAYS & Matrices SK Ahsan Why Search ? ■ Everyday life -We always Looking for something – builder yellow pages, universities, hairdressers ■ Computers can search ■ World wide web – ■ Spreadsheet – ■ Databases – ■ Large records – 1000s takes time - many comparison slow system – user wont wait long time
  • 25. ARRAYS & Matrices SK Ahsan Search Algorithms ■ Different types – Sequential Search – Binary Search ■ Discuss - search algorithms - analyze them ■ Analysis of the algorithms enables programmers to decide which algorithm to use for a specific application
  • 26. ARRAYS & Matrices SK Ahsan Some observations – Key ■ Each item in a data set - special member that uniquely identifies the item in the data set ■ For e.g University - a data set which contains student records – student ID uniquely identifies each student ■ This unique member of the item is called Key of the item
  • 27. ARRAYS & Matrices SK Ahsan Some observations - Key ■ Where can Keys of the item in a data set be used in ? ■ When searching the data set - for a particular item, what do we do ? ■ compare the key of the item for which we are searching - with the keys of the items in the data set – e.g if we looking particular student id in a list of student id exam results
  • 28. ARRAYS & Matrices SK Ahsan Analysis of Algorithms ■ In addition to describing the algorithms – analyse them ■ What does analysis of algorithms involve ? - key comparisons - Moreover – the number of key comparisons refers to - the number of times the key of the item (in search & sort algorithms) is compared with the keys of the items in the list
  • 29. ARRAYS & Matrices SK Ahsan Sequential search ■ Problem :- – we want to search for a given element in a list. ■ Do we know where the target element occurs?.
  • 30. ARRAYS & Matrices SK Ahsan Sequential Search Sequential search is also known as linear or serial search. It follows the following step to search a value in array. – Visit the first element of array and compare its value with required value. – If the value of array matches with the desired value, the search is complete. – If the value of array does not match, move to next element an repeat same process.
  • 31. ARRAYS & Matrices SK Ahsan 10 20 30 40 50 60 70 80 90 100 1 2 3 4 5 6 7 8 9 10 • Visit the first element of array and compare its value with required value. • If the value of array matches with the desired value, the search is complete. • If the value of array does not match, move to next element an repeat same process.
  • 32. ARRAYS & Matrices SK Ahsan • Visit the first element of array and compare its value with required value. • If the value of array matches with the desired value, the search is complete. • If the value of array does not match, move to next element an repeat same process. arr[1],10 = = 50 10 20 30 40 50 60 70 80 90 100 1 2 3 4 5 6 7 8 9 10
  • 33. ARRAYS & Matrices SK Ahsan • Visit the first element of array and compare its value with required value. • If the value of array matches with the desired value, the search is complete. • If the value of array does not match, move to next element an repeat same process. arr[2],20 = = 50 10 20 30 40 50 60 70 80 90 100 1 2 3 4 5 6 7 8 9 10
  • 34. ARRAYS & Matrices SK Ahsan • Visit the first element of array and compare its value with required value. • If the value of array matches with the desired value, the search is complete. • If the value of array does not match, move to next element an repeat same process. arr[3],30 = = 50 10 20 30 40 50 60 70 80 90 100 1 2 3 4 5 6 7 8 9 10
  • 35. ARRAYS & Matrices SK Ahsan • Visit the first element of array and compare its value with required value. • If the value of array matches with the desired value, the search is complete. • If the value of array does not match, move to next element an repeat same process. arr[4],40 = = 50 10 20 30 40 50 60 70 80 90 100 1 2 3 4 5 6 7 8 9 10
  • 36. ARRAYS & Matrices SK Ahsan • Visit the first element of array and compare its value with required value. • If the value of array matches with the desired value, the search is complete. • If the value of array does not match, move to next element an repeat same process. loc = i loc = 5 arr[5],50 = = 50 Example Code 1 10 20 30 40 50 60 70 80 90 100 1 2 3 4 5 6 7 8 9 10
  • 37. ARRAYS & Matrices SK Ahsan Binary Search Binary search is a quicker method of searching for value in the array. Binary search is very quick but it can only search an sorted array. It cannot be applied on an unsorted array. o It locates the middle element of array and compare with desired number. o If they are equal, search is successful and the index of middle element is returned. o If they are not equal, it reduces the search to half of the array. o If the search number is less than the middle element, it searches the first half of array. Otherwise it searches the second half of the array. The process continues until the required number is found or loop completes without successful search.
  • 38. ARRAYS & Matrices SK Ahsan Binary Search
  • 39. ARRAYS & Matrices SK Ahsan Binary Search: middle element left + right 2 mid =
  • 40. ARRAYS & Matrices SK Ahsan Binary Searchbool BinSearch(double list[ ], int n, double item, int&index){ int left=0; int right=n-1; int mid; while(left<=right){ mid=(left+right)/2; if(item> list [mid]){ left=mid+1; } else if(item< list [mid]){ right=mid-1;} else{ item= list [mid]; index=mid; return true; } }// while return false; }
  • 41. ARRAYS & Matrices SK Ahsan Binary Search: Example Example Code 1
  • 42. ARRAYS & Matrices SK Ahsan Sorting Arrays Sorting is a process of arranging the value of array in a particular order. An array can be sorted in two order. o Ascending Order o Descending Order 12 25 33 37 48 48 37 33 25 12
  • 43. ARRAYS & Matrices SK Ahsan Techniques Of Sorting Array There are two techniques of sorting array: o Selection Sort o Bubble Sort
  • 44. ARRAYS & Matrices SK Ahsan Bubble Sort Bubble Sort is also known as exchange sort. It repeatedly visits the array and compares two items at a time. It works as follows: o Compare adjacent element. If the first is greater than the second, swap them. o Repeat this for each pair of adjacent element, starting with the first two and ending with the last two. (at this point last element should be greatest). o Repeat the step for all elements except the last one. o Keep repeating for one fewer element each time until there are no pairs to compare.
  • 45. ARRAYS & Matrices SK Ahsan Bubble sort  Compare each element (except the last one) with its neighbor to the right  If they are out of order, swap them  This puts the largest element at the very end  The last element is now in the correct and final place  Compare each element (except the last two) with its neighbor to the right  If they are out of order, swap them  This puts the second largest element next to last  The last two elements are now in their correct and final places  Compare each element (except the last three) with its neighbor to the right  Continue as above until you have no unsorted elements on the left
  • 46. ARRAYS & Matrices SK Ahsan Example of bubble sort 7 2 8 5 4 2 7 8 5 4 2 7 8 5 4 2 7 5 8 4 2 7 5 4 8 2 7 5 4 8 2 5 7 4 8 2 5 4 7 8 2 7 5 4 8 2 5 4 7 8 2 4 5 7 8 2 5 4 7 8 2 4 5 7 8 2 4 5 7 8 (done)
  • 47. ARRAYS & Matrices SK Ahsan Analysis of bubble sort ■ Let n = a.length = size of the array ■ The outer loop is executed n-1 times (call it n, that’s close enough) ■ Each time the outer loop is executed, the inner loop is executed – Inner loop executes n-1 times at first, linearly dropping to just once – On average, inner loop executes about n/2 times for each execution of the outer loop – In the inner loop, the comparison is always done (constant time), the swap might be done (also constant time) ■ Result is n * n/2 * k, that is, O(n2/2 + k) = O(n2)
  • 48. ARRAYS & Matrices SK Ahsan Selection sort ■ Given an array of length n, – Search elements 0 through n-1 and select the smallest ■ Swap it with the element in location 0 – Search elements 1 through n-1 and select the smallest ■ Swap it with the element in location 1 – Search elements 2 through n-1 and select the smallest ■ Swap it with the element in location 2 – Search elements 3 through n-1 and select the smallest ■ Swap it with the element in location 3 – Continue in this fashion until there’s nothing left to search
  • 49. ARRAYS & Matrices SK Ahsan Selection Sort Selection sort is a technique that sort an array. It selects an element in the array and moves it to its proper position. Selection sort works as follows: 1. Find the minimum value in the list. 2. Swap it with value in the first position. 3. Sort the remainder of the list excluding the first value.
  • 50. ARRAYS & Matrices SK Ahsan Example and analysis of selection sort  The selection sort might swap an array element with itself--this is harmless, and not worth checking for  Analysis:  The outer loop executes n-1 times  The inner loop executes about n/2 times on average (from n to 2 times)  Work done in the inner loop is constant (swap two array elements)  Time required is roughly (n-1)*(n/2)  You should recognize this as O(n2) 7 2 8 5 4 2 7 8 5 4 2 4 8 5 7 2 4 5 8 7 2 4 5 7 8
  • 52. ARRAYS & Matrices SK Ahsan Selection Sort ■ Algorithm – Step 1 − Set MIN to location 0 – Step 2 − Search the minimum element in the list – Step 3 − Swap with value at location MIN – Step 4 − Increment MIN to point to next element – Step 5 − Repeat until list is sorted
  • 53. ARRAYS & Matrices SK Ahsan Selection sort ■ Pseudo code – procedure selection sort – list : array of items – n : size of list – for i = 1 to n - 1 – /* set current element as minimum*/ – min = i ; – /* check the element to be minimum */ – for j = i+1 to n – if list[j] < list[min] then – min = j ; – end if – end for – /* swap the minimum element with the current element*/ – if index Min != i then – swap list[min] and list[i] – end if – end for – end procedure EXAMPLE CODE 1 EXAMPLE CODE 2
  • 54. ARRAYS & Matrices SK Ahsan DRY RUN ■ Iteration 1 PASS 1 0 1 2 3 4 56 78 33 81 12
  • 55. ARRAYS & Matrices SK Ahsan DRY RUN ■ Iteration 2 PASS 1 0 1 2 3 4 56 78 33 81 12
  • 56. ARRAYS & Matrices SK Ahsan DRY RUN ■ Iteration 3 PASS 1 0 1 2 3 4 56 78 33 81 12
  • 57. ARRAYS & Matrices SK Ahsan DRY RUN ■ Iteration 4 PASS 1 0 1 2 3 4 56 78 33 81 12 12 78 33 81 56
  • 58. ARRAYS & Matrices SK Ahsan DRY RUN ■ Iteration 1 PASS 2 0 1 2 3 4 12 78 33 81 56
  • 59. ARRAYS & Matrices SK Ahsan DRY RUN ■ Iteration 2 PASS 2 0 1 2 3 4 12 78 33 81 56
  • 60. ARRAYS & Matrices SK Ahsan DRY RUN ■ Iteration 3 PASS 2 0 1 2 3 4 12 78 33 81 56 12 33 78 81 56
  • 61. ARRAYS & Matrices SK Ahsan DRY RUN ■ Iteration 1 PASS 3 0 1 2 3 4 12 33 78 81 56
  • 62. ARRAYS & Matrices SK Ahsan DRY RUN ■ Iteration 2 PASS 3 0 1 2 3 4 12 33 78 81 56 12 33 56 81 78
  • 63. ARRAYS & Matrices SK Ahsan DRY RUN ■ Iteration 1 PASS 4 0 1 2 3 4 12 33 56 81 78 12 33 56 78 81
  • 64. ARRAYS & Matrices SK Ahsan Bubble sort■ Algorithm – begin BubbleSort(list) – for all elements of list – if list[i] > list[i+1] – swap(list[i], list[i+1]) – end if – end for – – return list – end BubbleSort
  • 65. ARRAYS & Matrices SK Ahsan Bubble sort ■ Pseudo code – procedure bubbleSort( list : array of items ) – loop = list.count – for i = 0 to loop-1 do: – swapped = false – for j = 0 to loop-1 do: – /* compare the adjacent elements */ – if list[j] > list[j+1] then – /* swap them */ – swap( list[j], list[j+1] ) – swapped = true – end if – end for – /*if no number was swapped that means array is sorted now, break the loop.*/ – if(not swapped) then – break – end if – end for – end procedure return list
  • 66. ARRAYS & Matrices SK Ahsan Two-D Arrays Two-D array can be considered as table that consists of rows and columns. Each element in 2-D array is refered with the help of two indexes. One index indicates row and second indicates the column. Declaring 2-D Array: Data_type Identifier[row][column]; e.g: int arr[4][3]; o Data _type: Data type of values to be stored in the array. o Identifier: Name of the array. o Rows : # of Rows in the table of array. o Column : # of Columns in the table of array. 0,0 0,1 0,2 1,0 1,1 1,2 2,0 2,1 2,2 3,0 3,1 3,2
  • 67. ARRAYS & Matrices SK Ahsan Two-D array Intialization The two-D array can also be initialized at the time of declaration. Initialization is performed by assigning the initial values in braces seperated by commas. Some important points : o The elements of each row are enclosed within braces and seperated by comma. o All rows are enclosed within braces. o For number arrays, if all elements are not specified , the un specified elements are initialized by zero.
  • 68. ARRAYS & Matrices SK Ahsan Two-D array Intialization Syntax: int arr[4][3]={ {12,5,22}, {95,3,41}, {77,6,53}, {84,59,62} } 12 5 22 95 3 41 77 6 53 84 59 62 Column indexes Row indexes 0 2 1 3 10 2
  • 69. ARRAYS & Matrices SK Ahsan Case Study: Computing Mean, Median and Mode Using Arrays ■ Mean – Average (sum/number of elements) ■ Median – Number in middle of sorted list – 1, 2, 3, 4, 5 (3 is median) – If even number of elements, take average of middle two ■ Mode – Number that occurs most often – 1, 1, 1, 2, 3, 3, 4, 5 (1 is mode)
  • 70. ARRAYS & Matrices SK Ahsan Case Study ■Find Set Properties –Set Union –Set Differences