SlideShare a Scribd company logo
1 of 22
ARRAYS IN C
Arrays in C
 OUTLINE


♦ Review of Arrays in C
♦ Declaration and Initialization of Arrays
♦ Sorting: Bubble Sort
♦ Searching: Linear and Binary Search
Arrays
 Arrays are defined to be a sequence/set of data
  elements of the same type. Having an array, each
  array element can be accessed by its position in the
  sequence of the array.
♦ Decleration of the Arrays: Any array declaration
  contains: the array name, the element type and the
  array size.
 Examples:
 int a[20], b[3],c[7];
 float f[5], c[2];
 char m[4], n[20];
Arrays
 Initialisation of an array is the process of
  assigning initial values. Typically declaration
  and initialisation are combined.
 Examples:
 int a[4]={1,3,5,2};
 float, b[3]={2.0, 5.5, 3.14};
 char name[4]= {‘E’,’m’,’r’,’e’};
 int c[10]={0};
Example
 Write a program to calculate and print the average of the following array
    of integers.
   ( 4, 3, 7, -1, 7, 2, 0, 4, 2, 13)
   #include<stdio.h>
   #define size 10
   int main()
   {
   int x[10]={4,3,7,-1,7,2,0,4,2,13}, i, sum=0;
   float av;
   for(i=0,i<=size-1;i++)
   sum = sum + x[i];
   av = (float)sum/size;
   printf(“The average of the numbers=%.2fn”, av);
   return 0;
   }
Sorting
 Sorting an array is the ordering the array elements
  in ascending (increasing -from min to max) or
  descending (decreasing – from max to min) order.
 Example:
 {2 1 5 3 2} →{1, 2, 2, 3, 5} ascending order
 {2 1 5 3 2} →{5, 3, 2, 2, 1} descending order
Bubble Sort
 Smaller values in the list gradually “bubble”
  their way upward to the top of the array.
 The technique makes several passes through
  the array. On each pass successive pairs of
  elements are compared. If the pair is in
  increasing order (or equal) the pair is
  unchanged. If a pair is in descending order,
  their values are swapped in the array:
Bubble Sort
Pass = 1          Pass = 2           Pass = 3           Pass=4

  21532              12325              12235            12235

  12532              12325              12235            12235

  12532              12325              12235            12235

  12352              12235              12235            12235

  12325              12235              12235            12235
Underlined pairs show the comparisons. For each pass there are size-1
 comparisons.
Total number of comparisons= (size-1)2
Bubble Sort C Code
   /* This program sorts the array elements in the ascending order*/
   #include <stdio.h>
   #define SIZE 5
   void BubbleSort(int [ ]);
   int main()
   {
   int a[SIZE]= {2,1,5,3,2};
   int i;
   printf(“The elements of the array before sortingn”);
   for (i=0; i<= SIZE-1; i++)
   printf(“%4d”, a[i]);
   BubbleSort(a);
   printf(“nnThe elements of the array after sortingn”);
   for (i=0; i<= SIZE-1; i++)
   printf(“%4d”, a[i]);
   return 0;
   }
void BubbleSort(int A[ ])
   void BubbleSort(int A[ ])
   {
   int i, pass, hold;
   for (pass=1; pass<= SIZE-1; pass++){
       for (i=0; i<= SIZE-2; i++) {
       if(A[i] >A[i+1]){
           hold =A[i];

           A[i]=A[i+1];

           A[i+1]=hold;

           }

       }
 }
 }
Example
 Write a program to determine the median of
  the array given below:
        (9, 4, 5, 1, 7, 78, 22, 15, 96, 45)
 Note that the median of an array is the middle
  element of a sorted array.
Example
/* This program determines the median of an array*/
#include <stdio.h>
#define SIZE 10
void BubbleSort(int []);
int main()
{
int a[SIZE]= {9, 4, 5, 1, 7, 78, 22, 15, 96, 45}, median;
int i;
printf(“The elements of the input array isn”);
for (i=0; i<= SIZE-1; i++)
printf(“%4d”, a[i]);
BoubleSort(a);
printf(“The elements of the sorted array isn”);
for (i=0; i<= SIZE-1; i++)
printf(“%4d”, a[i]);
median = a[SIZE/2];
printf(“The median of the array is=%d”, median);
return 0;
}
Example
  void BubbleSort(int A[ ])
  {
  int i, pass, hold;
  for (pass=1; pass<= SIZE-1; pass++){
  for (i=0; i<= SIZE-2; i++) {
  if(A[i] >A[i+1]){
  hold =A[i];
  A[i]=A[i+1];
  A[i+1]=hold;
  }
  }
  }
  }
Searching
 The process of finding a particular element of an
  array is called searching. There two popularsearching
  techniques:
 Linear search and binary search.
 The linear search compares each array element with
  the search key.
 If the search key is a member of the array, typically
  the location of the search key is reported to indicate
  the presence of the search key in the array.
  Otherwise, a sentinel value is reported to indicate the
  presence of the search key in the array.
Linear Search
 Each member of the array is visited until the
  search key is found.
 Example:
 Write a program to search for the search key
  entered by the user in the following array:
        (9, 4, 5, 1, 7, 78, 22, 15, 96, 45)
 You can use the linear search in this
  example.
Linear Search
   /* This program is an example of the Linear Search*/
   #include <stdio.h>
   #define SIZE 10
   int LinearSearch(int [], int);
   int main()
   {
   int a[SIZE]= {9, 4, 5, 1, 7, 78, 22, 15, 96, 45}, key, pos;
   printf(“Enter the Search Keyn”);
   scanf(“%d”,&key);
   pos = LinearSearch(a, key);
   if(pos == -1)
   printf(“The search key is not in the arrayn”);
   else
   printf(“The search key %d is at location %dn”, key, pos);
   return 0;
   }
int LinearSearch (int b[ ], int skey)
int LinearSearch (int b[ ], int skey)
{
int i;
for (i=0; i<= SIZE-1; i++)
if(b[i] == skey)
return i;
return -1;
}
Binary Search
 Given a sorted array Binary Search
  algorithm can be used to perform fast
  searching of a search key on the sorted array.
 The following program uses pointer notation
  to implement the binary search algorithm for
  the search key entered by the user in the
  following array:
       (3, 5, 9, 11, 15, 17, 22, 25, 37, 68)
Binary Search
 #include <stdio.h>
 #define SIZE 10
 int BinarySearch(int [ ], int);
 int main()
 {
 int a[SIZE]= {3, 5, 9, 11, 15, 17, 22, 25, 37, 68}, key, pos;
 printf(“Enter the Search Keyn”);
 scanf(“%d”,&key);
 pos = BinarySearch(a, key);
 if(pos == -1)
 printf(“The search key is not in the arrayn”);
 else
 printf(“The search key %d is at location %dn”, key, pos);
 return 0;
 }
int BinarySearch (int A[], int skey)
  int BinarySearch (int A[], int skey)
  {
  int low=0,high=SIZE-1,middle;
  while(low <= high){
      middle= (low+high)/2;
      if(skey == A[middle])
         return middle;
      else if(skey <A[middle])
                high = middle-1;
            else
                low = middle+1;
      }
  return -1;
  }
Computational Complexity
 The Computational Complexity of the Binary
    Search algorithm is measured by the maximum
    (worst case) number of Comparisons it performs for
    searching operations.
   The searched array is divided by 2 for each
    comparison/iteration.
   Therefore, the maximum number of comparisons is
    measured by:
   log2(n) where n is the size of the array
   Example:
   If a given sorted array 1024 elements, then the
    maximum number of comparisons required is:
   log2(1024) = 10 (only 10 comparisons is enough)
Computational Complexity
 Note that the Computational Complexity of the
  Linear Search is the maximum number of
  comparisons you need to search the array. As you
  are visiting all the array elements in the worst case,
  then, the number of comparisons required is:
               n (n is the size of the array)
 Example:
 If a given an array of 1024 elements, then the
  maximum number of comparisons required is:
   n = 1024 (As many as 1024 comparisons may be
                           required)

More Related Content

What's hot

What's hot (20)

C++ lecture 04
C++ lecture 04C++ lecture 04
C++ lecture 04
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
C Programming : Arrays
C Programming : ArraysC Programming : Arrays
C Programming : Arrays
 
C arrays
C arraysC arrays
C arrays
 
Arrays basics
Arrays basicsArrays basics
Arrays basics
 
Array in C
Array in CArray in C
Array in C
 
Lecture 15 - Array
Lecture 15 - ArrayLecture 15 - Array
Lecture 15 - Array
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional array
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Multi dimensional array
Multi dimensional arrayMulti dimensional array
Multi dimensional array
 
Arrays
ArraysArrays
Arrays
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Arrays in C
Arrays in CArrays in C
Arrays in C
 
Programming in c arrays
Programming in c   arraysProgramming in c   arrays
Programming in c arrays
 
2D Array
2D Array 2D Array
2D Array
 
Pf presntation
Pf presntationPf presntation
Pf presntation
 
Array in c
Array in cArray in c
Array in c
 
C++ programming (Array)
C++ programming (Array)C++ programming (Array)
C++ programming (Array)
 
Unit 6. Arrays
Unit 6. ArraysUnit 6. Arrays
Unit 6. Arrays
 
1 D Arrays in C++
1 D Arrays in C++1 D Arrays in C++
1 D Arrays in C++
 

Viewers also liked

Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to c
Hattori Sidek
 
Looping statements in C
Looping statements in CLooping statements in C
Looping statements in C
Jeya Lakshmi
 
Tp1 compte rendu en langage c
Tp1 compte rendu en langage cTp1 compte rendu en langage c
Tp1 compte rendu en langage c
Ebrima NJIE
 

Viewers also liked (20)

Statements in C
Statements in CStatements in C
Statements in C
 
Control structuresin c
Control structuresin cControl structuresin c
Control structuresin c
 
Programming in C Session 1
Programming in C Session 1Programming in C Session 1
Programming in C Session 1
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
C – A Programming Language- I
C – A Programming Language- IC – A Programming Language- I
C – A Programming Language- I
 
HTML Basics 1 workshop
HTML Basics 1 workshopHTML Basics 1 workshop
HTML Basics 1 workshop
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
 
How to Create an Array & types in PHP
How to Create an Array & types in PHP How to Create an Array & types in PHP
How to Create an Array & types in PHP
 
Arrays In C Language
Arrays In C LanguageArrays In C Language
Arrays In C Language
 
BASICS OF HTML
BASICS OF HTMLBASICS OF HTML
BASICS OF HTML
 
HTML Start Up - Introduction to HTML
HTML Start Up - Introduction to HTMLHTML Start Up - Introduction to HTML
HTML Start Up - Introduction to HTML
 
HTML basics
HTML basicsHTML basics
HTML basics
 
Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to c
 
Looping statements in C
Looping statements in CLooping statements in C
Looping statements in C
 
Tp1 compte rendu en langage c
Tp1 compte rendu en langage cTp1 compte rendu en langage c
Tp1 compte rendu en langage c
 
9. statements (conditional statements)
9. statements (conditional statements)9. statements (conditional statements)
9. statements (conditional statements)
 
C programming
C programmingC programming
C programming
 
C tutorials
C tutorialsC tutorials
C tutorials
 
Basics of HTML 5 for Beginners
Basics of HTML 5 for Beginners Basics of HTML 5 for Beginners
Basics of HTML 5 for Beginners
 
HTML - Basics and Good Practices
HTML - Basics and Good PracticesHTML - Basics and Good Practices
HTML - Basics and Good Practices
 

Similar to Arrays

CP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdfCP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdf
saneshgamerz
 
presentation_arrays_1443553113_140676.ppt
presentation_arrays_1443553113_140676.pptpresentation_arrays_1443553113_140676.ppt
presentation_arrays_1443553113_140676.ppt
NamakkalPasanga
 

Similar to Arrays (20)

CP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdfCP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdf
 
Arrays searching-sorting
Arrays searching-sortingArrays searching-sorting
Arrays searching-sorting
 
SlideSet_4_Arraysnew.pdf
SlideSet_4_Arraysnew.pdfSlideSet_4_Arraysnew.pdf
SlideSet_4_Arraysnew.pdf
 
Data structures arrays
Data structures   arraysData structures   arrays
Data structures arrays
 
Arrays
ArraysArrays
Arrays
 
Unit 2 dsa LINEAR DATA STRUCTURE
Unit 2 dsa LINEAR DATA STRUCTUREUnit 2 dsa LINEAR DATA STRUCTURE
Unit 2 dsa LINEAR DATA STRUCTURE
 
UNIT V.docx
UNIT V.docxUNIT V.docx
UNIT V.docx
 
CSEG1001Unit 3 Arrays and Strings
CSEG1001Unit 3 Arrays and StringsCSEG1001Unit 3 Arrays and Strings
CSEG1001Unit 3 Arrays and Strings
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
1D Array
1D Array1D Array
1D Array
 
VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2
 
C_Arrays.pptx
C_Arrays.pptxC_Arrays.pptx
C_Arrays.pptx
 
presentation_arrays_1443553113_140676.ppt
presentation_arrays_1443553113_140676.pptpresentation_arrays_1443553113_140676.ppt
presentation_arrays_1443553113_140676.ppt
 
07+08slide.pptx
07+08slide.pptx07+08slide.pptx
07+08slide.pptx
 
02 arrays
02 arrays02 arrays
02 arrays
 
DS Unit 1.pptx
DS Unit 1.pptxDS Unit 1.pptx
DS Unit 1.pptx
 
array
arrayarray
array
 
design and analysis of algorithm Lab files
design and analysis of algorithm Lab filesdesign and analysis of algorithm Lab files
design and analysis of algorithm Lab files
 
Array
ArrayArray
Array
 
UNIT IV -Data Structures.pdf
UNIT IV -Data Structures.pdfUNIT IV -Data Structures.pdf
UNIT IV -Data Structures.pdf
 

Recently uploaded

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Recently uploaded (20)

2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 

Arrays

  • 2. Arrays in C  OUTLINE ♦ Review of Arrays in C ♦ Declaration and Initialization of Arrays ♦ Sorting: Bubble Sort ♦ Searching: Linear and Binary Search
  • 3. Arrays  Arrays are defined to be a sequence/set of data elements of the same type. Having an array, each array element can be accessed by its position in the sequence of the array. ♦ Decleration of the Arrays: Any array declaration contains: the array name, the element type and the array size.  Examples:  int a[20], b[3],c[7];  float f[5], c[2];  char m[4], n[20];
  • 4. Arrays  Initialisation of an array is the process of assigning initial values. Typically declaration and initialisation are combined.  Examples:  int a[4]={1,3,5,2};  float, b[3]={2.0, 5.5, 3.14};  char name[4]= {‘E’,’m’,’r’,’e’};  int c[10]={0};
  • 5. Example  Write a program to calculate and print the average of the following array of integers.  ( 4, 3, 7, -1, 7, 2, 0, 4, 2, 13)  #include<stdio.h>  #define size 10  int main()  {  int x[10]={4,3,7,-1,7,2,0,4,2,13}, i, sum=0;  float av;  for(i=0,i<=size-1;i++)  sum = sum + x[i];  av = (float)sum/size;  printf(“The average of the numbers=%.2fn”, av);  return 0;  }
  • 6. Sorting  Sorting an array is the ordering the array elements in ascending (increasing -from min to max) or descending (decreasing – from max to min) order.  Example:  {2 1 5 3 2} →{1, 2, 2, 3, 5} ascending order  {2 1 5 3 2} →{5, 3, 2, 2, 1} descending order
  • 7. Bubble Sort  Smaller values in the list gradually “bubble” their way upward to the top of the array.  The technique makes several passes through the array. On each pass successive pairs of elements are compared. If the pair is in increasing order (or equal) the pair is unchanged. If a pair is in descending order, their values are swapped in the array:
  • 8. Bubble Sort Pass = 1 Pass = 2 Pass = 3 Pass=4 21532 12325 12235 12235 12532 12325 12235 12235 12532 12325 12235 12235 12352 12235 12235 12235 12325 12235 12235 12235 Underlined pairs show the comparisons. For each pass there are size-1 comparisons. Total number of comparisons= (size-1)2
  • 9. Bubble Sort C Code  /* This program sorts the array elements in the ascending order*/  #include <stdio.h>  #define SIZE 5  void BubbleSort(int [ ]);  int main()  {  int a[SIZE]= {2,1,5,3,2};  int i;  printf(“The elements of the array before sortingn”);  for (i=0; i<= SIZE-1; i++)  printf(“%4d”, a[i]);  BubbleSort(a);  printf(“nnThe elements of the array after sortingn”);  for (i=0; i<= SIZE-1; i++)  printf(“%4d”, a[i]);  return 0;  }
  • 10. void BubbleSort(int A[ ])  void BubbleSort(int A[ ])  {  int i, pass, hold;  for (pass=1; pass<= SIZE-1; pass++){  for (i=0; i<= SIZE-2; i++) {  if(A[i] >A[i+1]){  hold =A[i];  A[i]=A[i+1];  A[i+1]=hold;  }  }  }  }
  • 11. Example  Write a program to determine the median of the array given below: (9, 4, 5, 1, 7, 78, 22, 15, 96, 45)  Note that the median of an array is the middle element of a sorted array.
  • 12. Example /* This program determines the median of an array*/ #include <stdio.h> #define SIZE 10 void BubbleSort(int []); int main() { int a[SIZE]= {9, 4, 5, 1, 7, 78, 22, 15, 96, 45}, median; int i; printf(“The elements of the input array isn”); for (i=0; i<= SIZE-1; i++) printf(“%4d”, a[i]); BoubleSort(a); printf(“The elements of the sorted array isn”); for (i=0; i<= SIZE-1; i++) printf(“%4d”, a[i]); median = a[SIZE/2]; printf(“The median of the array is=%d”, median); return 0; }
  • 13. Example void BubbleSort(int A[ ]) { int i, pass, hold; for (pass=1; pass<= SIZE-1; pass++){ for (i=0; i<= SIZE-2; i++) { if(A[i] >A[i+1]){ hold =A[i]; A[i]=A[i+1]; A[i+1]=hold; } } } }
  • 14. Searching  The process of finding a particular element of an array is called searching. There two popularsearching techniques:  Linear search and binary search.  The linear search compares each array element with the search key.  If the search key is a member of the array, typically the location of the search key is reported to indicate the presence of the search key in the array. Otherwise, a sentinel value is reported to indicate the presence of the search key in the array.
  • 15. Linear Search  Each member of the array is visited until the search key is found.  Example:  Write a program to search for the search key entered by the user in the following array: (9, 4, 5, 1, 7, 78, 22, 15, 96, 45)  You can use the linear search in this example.
  • 16. Linear Search  /* This program is an example of the Linear Search*/  #include <stdio.h>  #define SIZE 10  int LinearSearch(int [], int);  int main()  {  int a[SIZE]= {9, 4, 5, 1, 7, 78, 22, 15, 96, 45}, key, pos;  printf(“Enter the Search Keyn”);  scanf(“%d”,&key);  pos = LinearSearch(a, key);  if(pos == -1)  printf(“The search key is not in the arrayn”);  else  printf(“The search key %d is at location %dn”, key, pos);  return 0;  }
  • 17. int LinearSearch (int b[ ], int skey) int LinearSearch (int b[ ], int skey) { int i; for (i=0; i<= SIZE-1; i++) if(b[i] == skey) return i; return -1; }
  • 18. Binary Search  Given a sorted array Binary Search algorithm can be used to perform fast searching of a search key on the sorted array.  The following program uses pointer notation to implement the binary search algorithm for the search key entered by the user in the following array: (3, 5, 9, 11, 15, 17, 22, 25, 37, 68)
  • 19. Binary Search #include <stdio.h> #define SIZE 10 int BinarySearch(int [ ], int); int main() { int a[SIZE]= {3, 5, 9, 11, 15, 17, 22, 25, 37, 68}, key, pos; printf(“Enter the Search Keyn”); scanf(“%d”,&key); pos = BinarySearch(a, key); if(pos == -1) printf(“The search key is not in the arrayn”); else printf(“The search key %d is at location %dn”, key, pos); return 0; }
  • 20. int BinarySearch (int A[], int skey) int BinarySearch (int A[], int skey) { int low=0,high=SIZE-1,middle; while(low <= high){ middle= (low+high)/2; if(skey == A[middle]) return middle; else if(skey <A[middle]) high = middle-1; else low = middle+1; } return -1; }
  • 21. Computational Complexity  The Computational Complexity of the Binary Search algorithm is measured by the maximum (worst case) number of Comparisons it performs for searching operations.  The searched array is divided by 2 for each comparison/iteration.  Therefore, the maximum number of comparisons is measured by:  log2(n) where n is the size of the array  Example:  If a given sorted array 1024 elements, then the maximum number of comparisons required is:  log2(1024) = 10 (only 10 comparisons is enough)
  • 22. Computational Complexity  Note that the Computational Complexity of the Linear Search is the maximum number of comparisons you need to search the array. As you are visiting all the array elements in the worst case, then, the number of comparisons required is: n (n is the size of the array)  Example:  If a given an array of 1024 elements, then the maximum number of comparisons required is: n = 1024 (As many as 1024 comparisons may be required)