Docsity

Data Structures: Performance, Complexity, Searching & Sorting, Study notes of Data Structures and Algorithms

Partial preview of the text

Download Data Structures: Performance, Complexity, Searching & Sorting and more Study notes Data Structures and Algorithms in PDF only on Docsity!

LECTURE NOTES

on

DATA STRUCTURE S

I B. Tec h II Se m e s t e r (R1 7 )

Mr. K Mun iv ar a Pras a d , Ass o c i a t e Prof e s s o r

CHADALAWADA RAMANAMMA ENGINEERING COLLEGE

(AUTONOMOUS)

Chadalawada Nagar, Renigunta Road, Tirupati – 517 506

Department of Computer Science and Engineering

UNIT-I

PROGRAM M I N G PERFOR MA N CE

Perf o r m a n c e of a pro g r a m : The perfor m a n c e of a progra m is meas u r e d base d on the amou n t of comp u t e r me m o r y and time nee d e d to run a progra m. The two appr o a c h e s which are use d to meas u r e the perfor m a n c e of the progr a m are:

1. Anal y t i c a l m e t h o d à called the Perfor m a n c e Analysis. 2. Exp e r i m e n t a l m e t h o d à called the Perfor m a n c e Measu r e m e n t. SPACE COMPLEXITY Sp a c e co m p l e x i t y : The Spac e com pl e xi t y of a progra m is define d as the amou n t of me m o r y it need s to run to com pl e tio n. As said above the spac e complexity is one of the factor which accou n t s for the perfor m a n c e of the progr a m. The spac e complexity can be mea s u r e d using expe ri m e n t a l met ho d, which is done by run ni n g the progr a m and then meas u r i n g the actu al spac e occupie d by the progr a m durin g execu tio n. But this is done very rarely. We estim a t e the spac e compl exity of the prog r a m before run nin g the prog r a m. Spa c e co m p l e x i t y is the su m of the foll o w i n g co m p o n e n t s : (i) Ins t r u c t i o n sp a c e : The prog r a m which is writt e n by the use r is the sourc e prog r a m. When this prog r a m is compile d, a compile d version of the prog r a m is gene r a t e d. For executi n g the prog r a m an execu t a bl e version of the progr a m is gen e r a t e d. The spac e occupi e d by these thre e when the progr a m is und e r execu tio n, will accou n t for the instr u c tio n spac e. (ii) Dat a sp a c e : The spac e nee d e d by the const a n t s , simple varia bl e s, arr ays , stru c t u r e s and othe r dat a struc t u r e s will accou n t for the data spac e. The Data space depe n d s on the followin g factors:Struc t u r e size – It is the sum of the size of compo n e n t variabl e s of the struc t u r e.  Array size – Total size of the array is the prod u c t of the size of the dat a type and the num b e r of array locations.

The total time take n for the exec utio n of the prog r a m is the sum of the compilatio n time and the executio n time. (i) Com pi l e tim e – The time take n for the compilatio n of the progr a m to prod u c e the inter m e d i a t e object code or the compile r version of the prog r a m. The compilatio n time is take n only once as it is enou g h if the prog r a m is compile d once. If optimize d code is to be gen e r a t e d , then the compila tion time will be high e r. (ii) Run tim e or Exe c u t i o n ti m e - The time take n for the execu tion of the progr a m. The optimiz e d code will take less time to get exec ut e d. Ti m e co m p l e x i t y T(P ) = c + T (^) p c à Compile time Tp à Run time or execu tio n time We will be inte r e s t e d in estim a ti n g only the executio n time as this is the one which varies accor di n g to the user input. Esti m a t i n g the Exec u t i o n tim e: Pro g r a m st e p : Progra m step is a mea nin g f ul seg m e n t of a progra m whic h is inde p e n d e n t of instan c e charact eristic s. Instan c e charac t eris tic s are the variables whose values are decid e d by the user input at that instant of time. Ste p s in esti m a ti n g the exec u tio n time of progra m: (i) Identify one or more key oper a tio n s and dete r m i n e the num b e r of times thes e are perfor m e d. That is find out how many key oper a tio n s are pres e n t inside a loop and how many time s that loop is execu t e d. (ii) Dete r mi n e the total num b e r of step s execut e d by the prog r a m. The time complexity will be propo r tio n al to the sum of the above two. ASYMPTOTIC NOTATIO N S Asympt otic nota tio n s – Asympt otic nota tio n s are the nota tio n s used to desc rib e the beh avior of the time or spac e compl exity. Let us rep r e s e n t the time complexity and the spac e complexity using the com m o n function f(n). The various asym p t o ti c nota tio n s are: (i) O ( Big Oh notation )

(ii) Ω( Ome g a notation ) (iii) θ ( Theta notation ) (iv) o ( Little Oh notation ) O – Big Oh notation The big Oh nota tion provide s an upp e r boun d for the function f(n). The function f(n) = O(g(n)) if and only if the r e exists positive const a n t s c and n 0 such that f(n) ≤ cg(n) for all n ≥ n 0. Exam pl e s:

  1. f(n) = 3n + 2 Let us take g(n) = n c = 4 n 0 = 2 Let us check the above condition 3n + 1 ≤ 4n for all n ≥ 2 The condition is satisfied. Henc e f(n) = O(n).
  2. f(n) = 10n 2 + 4n + 2 Let us take g(n) = n 2 c = 11 n 0 = 6 Let us check the above condition 10n 2 + 4n + 2 ≤ 11n for all n ≥ 6 The condition is satisfied. Henc e f(n) = O(n 2 ). Ω - Ome g a nota tion The Ωnotatio n gives the lower boun d for the function f(n). The function f(n) = Ω(g(n)) if and only if ther e exists positive const a n t s c and n 0 such that f(n) ≥ cg(n) for all n ≥ n 0. Exam pl e s:
  3. f(n) = 3n + 2 Let us take g(n) = n c = 3 n 0 = 0

SEARCHING AND SORTING

Searching is used to find the location where an element is available. There are two types of search techniques. They are:

  1. Linear or sequential search
  2. Binary search Sorting allows an efficient arrangement of elements within a given data structure. It is a way in which the elements are organized systematically for some purpose. For example, a dictionary in which words are arranged in alphabetical order and telephone director in which the subscriber names are listed in alphabetical order. There are many sorting techniques out of which we study the following.
  3. Bubble sort
  4. Quick sort
  5. Selection sort and
  6. Heap sort LINEAR SEARCH This is the simplest of all searching techniques. In this technique, an ordered or unordered list will be searched one by one from the beginning until the desired element is found. If the desired element is found in the list then the search is successful otherwise unsuccessful. Suppose there are ‘n ’ elements organized sequentially on a List. The number of comparisons required to retrieve an element from the list, purely depends on where the element is stored in the list. If it is the first element, one comparison will do; if it is second element two comparisons are necessary and so on. On an average you need [(n+1)/2] comparison’s to search an element. If search is not successful, you would need ’n ’ comparisons. The time complexity of linear search is O(n). Algorithm: Let array a[n] stores n elements. Determine whether element ‘x’ is present or not. linsrch (a[n], x) { index = 0; flag = 0; while (index < n) do { if (x == a[index]) { flag = 1; break; } index ++; } if(flag == 1) printf(“Data found at %d position“, index); else printf(“data not found”); }

Example 1: Suppose we have the following unsorted list: 45, 39, 8, 54, 77, 38, 24, 16, 4, 7, 9, 20 If we are searching for: 45, we’ll look at 1 element before success 39, we’ll look at 2 elements before success 8, we’ll look at 3 elements before success 54, we’ll look at 4 elements before success 77, we’ll look at 5 elements before success 38 we’ll look at 6 elements before success 24, we’ll look at 7 elements before success 16, we’ll look at 8 elements before success 4, we’ll look at 9 elements before success 7, we’ll look at 10 elements before success 9, we’ll look at 11 elements before success 20, we’ll look at 12 elements before success For any element not in the list, we’ll look at 12 elements before failure Example 2: Let us illustrate linear search on the following 9 elements: Index 0 1 2 3 4 5 6 7 8 Elements -15 -6 0 7 9 23 54 82 101 Searching different elements is as follows:

  1. Searching for x = 7 Search successful, data found at 3rd^ position
  2. Searching for x = 82 Search successful, data found at 7th^ position
  3. Searching for x = 42 Search un-successful, data not found A non-recursive program for Linear Search:

include

include

main() { int number[25], n, data, i, flag = 0; clrscr(); printf("\n Enter the number of elements: "); scanf("%d", &n); printf("\n Enter the elements: "); for(i = 0; i < n; i++) scanf("%d", &number[i]); printf("\n Enter the element to be Searched: "); scanf("%d", &data); for( i = 0; i < n; i++) { if(number[i] == data) { flag = 1; break; } } if(flag == 1) printf("\n Data found at location: %d", i+1); else printf("\n Data not found ");

Let array a[n] of elements in increasing order, n  0, determine whether ‘x’ is present, and if so, set j such that x = a[j] else return 0. binsrch (a[], n, x) { low = 1; high = n; while (low < high) do { mid =  (low + high)/2  if (x < a[mid]) high = mid – 1; else if (x > a[mid]) low = mid + 1; else return mid; } return 0; } low and high are integer variables such that each time through the loop either ‘x’ is found or low is increased by at least one or high is decreased by at least one. Thus we have two sequences of integers approaching each other and eventually low will become greater than high causing termination in a finite number of steps if ‘x’ is not present. Example 1: Let us illustrate binary search on the following 12 elements: Index 1 2 3 4 5 6 7 8 9 10 11 12 Elements 4 7 8 9 16 20 24 38 39 45 54 77 If we are searching for x = 4: (This needs 3 comparisons) low = 1, high = 12, mid = 13/2 = 6, check 20 low = 1, high = 5, mid = 6/2 = 3, check 8 low = 1, high = 2, mid = 3/2 = 1, check 4, found If we are searching for x = 7: (This needs 4 comparisons) low = 1, high = 12, mid = 13/2 = 6, check 20 low = 1, high = 5, mid = 6/2 = 3, check 8 low = 1, high = 2, mid = 3/2 = 1, check 4 low = 2, high = 2, mid = 4/2 = 2, check 7, found If we are searching for x = 8: (This needs 2 comparisons) low = 1, high = 12, mid = 13/2 = 6, check 20 low = 1, high = 5, mid = 6/2 = 3, check 8 , found If we are searching for x = 9: (This needs 3 comparisons) low = 1, high = 12, mid = 13/2 = 6, check 20 low = 1, high = 5, mid = 6/2 = 3, check 8 low = 4, high = 5, mid = 9/2 = 4, check 9, found If we are searching for x = 16: (This needs 4 comparisons) low = 1, high = 12, mid = 13/2 = 6, check 20 low = 1, high = 5, mid = 6/2 = 3, check 8 low = 4, high = 5, mid = 9/2 = 4, check 9 low = 5, high = 5, mid = 10/2 = 5, check 16, found If we are searching for x = 20: (This needs 1 comparison) low = 1, high = 12, mid = 13/2 = 6, check 20, found If we are searching for x = 24: (This needs 4 comparisons) low = 1, high = 12, mid = 13/2 = 6, check 20 low = 7, high = 12, mid = 19/2 = 9, check 39 low = 7, high = 10, mid = 17/2 = 8, check 38

low = 7, high = 7, mid = 14/2 = 7, check 24, found If we are searching for x = 38: (This needs 3 comparisons) low = 1, high = 12, mid = 13/2 = 6, check 20 low = 7, high = 12, mid = 19/2 = 9, check 39 low = 7, high = 10, mid = 17/2 = 8, check 38, found If we are searching for x = 39: (This needs 2 comparisons) low = 1, high = 12, mid = 13/2 = 6, check 20 low = 7, high = 12, mid = 19/2 = 9, check 39, found If we are searching for x = 45: (This needs 4 comparisons) low = 1, high = 12, mid = 13/2 = 6, check 20 low = 7, high = 12, mid = 19/2 = 9, check 39 low = 10, high = 12, mid = 22/2 = 11, check 54 low = 10, high = 10, mid = 20/2 = 10, check 45, found If we are searching for x = 54: (This needs 3 comparisons) low = 1, high = 12, mid = 13/2 = 6, check 20 low = 7, high = 12, mid = 19/2 = 9, check 39 low = 10, high = 12, mid = 22/2 = 11, check 54, found If we are searching for x = 77: (This needs 4 comparisons) low = 1, high = 12, mid = 13/2 = 6, check 20 low = 7, high = 12, mid = 19/2 = 9, check 39 low = 10, high = 12, mid = 22/2 = 11, check 54 low = 12, high = 12, mid = 24/2 = 12, check 77, found The number of comparisons necessary by search element: 20 – requires 1 comparison; 8 and 39 – requires 2 comparisons; 4, 9, 38, 54 – requires 3 comparisons; and 7, 16, 24, 45, 77 – requires 4 comparisons Summing the comparisons, needed to find all twelve items and dividing by 12, yielding 37/12 or approximately 3.08 comparisons per successful search on the average. Example 2: Let us illustrate binary search on the following 9 elements: Index 1 2 3 4 5 6 7 8 9 Elements -15 -6 0 7 9 23 54 82 101 The number of comparisons required for searching different elements is as follows:

  1. If we are searching for x = 101: (Number of comparisons = 4) low high mid 1 9 5 6 9 7 8 9 8 9 9 9 found
  2. Searching for x = 82: (Number of comparisons = 3) low high mid 1 9 5 6 9 7 8 9 8 found
  3. Searching for x = 42: (Number of comparisons = 4)

{ flag = 1; break; } else { if(data < number[mid]) high = mid - 1; else low = mid + 1; } } if(flag == 1) printf("\n Data found at location: %d", mid + 1); else printf("\n Data Not Found "); } A recursive program for binary search:

include

include

void bin_search(int a[], int data, int low, int high) { int mid ; if( low <= high) { mid = (low + high)/2; if(a[mid] == data) printf("\n Element found at location: %d ", mid + 1); else { if(data < a[mid]) bin_search(a, data, low, mid-1); else bin_search(a, data, mid+1, high); } } else printf("\n Element not found"); } void main() { int a[25], i, n, data; clrscr(); printf("\n Enter the number of elements: "); scanf("%d", &n); printf("\n Enter the elements in ascending order: "); for(i = 0; i < n; i++) scanf("%d", &a[i]); printf("\n Enter the element to be searched: "); scanf("%d", &data); bin_search(a, data, 0, n-1); getch(); } Bubble Sort: The bubble sort is easy to understand and program. The basic idea of bubble sort is to pass through the file sequentially several times. In each pass, we compare each element in the file with its

successor i.e., X[i] with X[i+1] and interchange two element when they are not in proper order. We will illustrate this sorting technique by taking a specific example. Bubble sort is also called as exchange sort. Consider the array x[n] which is stored in memory as shown below: X[0] X[1] X[2] X[3] X[4] X[5] 33 44 22 11 66 55 Suppose we want our array to be stored in ascending order. Then we pass through the array 5 times as described below: Pass 1: (first element is compared with all other elements) We compare X[i] and X[i+1] for i = 0, 1, 2, 3, and 4, and interchange X[i] and X[i+1] if X[i] > X[i+1]. The process is shown below: X[0] X[1] X[2] X[3] X[4] X[5] Remarks 33 44 22 11 66 55 22 44 11 44 44 66 55 66 33 22 11 44 55 66 The biggest number 66 is moved to (bubbled up) the right most position in the array. Pass 2: (second element is compared) We repeat the same process, but this time we don’t include X[5] into our comparisons. i.e., we compare X[i] with X[i+1] for i=0, 1, 2, and 3 and interchange X[i] and X[i+1] if X[i] > X[i+1]. The process is shown below: X[0] X[1] X[2] X[3] X[4] Remarks 33 22 11 44 55 22 33 11 33 33 44 44 55 22 11 33 44 55 The second biggest number 55 is moved now to X[4]. Pass 3: (third element is compared) We repeat the same process, but this time we leave both X[4] and X[5]. By doing this, we move the third biggest number 44 to X[3]. X[0] X[1] X[2] X[3] Remarks 22 11 33 44 11 22

printf ("%5d", x[i]); } Time Complexity: The bubble sort method of sorting an array of size n requires (n-1) passes and (n-1) comparisons on each pass. Thus the total number of comparisons is (n-1) * (n-1) = n^2 – 2n + 1, which is O(n^2 ). Therefore bubble sort is very inefficient when there are more elements to sorting. Selection Sort: Now, you will learn another sorting technique, which is more efficient than bubble sort and the insertion sort. This sort, as you will see, will not require no more than n-1 interchanges. The sort we are talking about is selection sort. Suppose x is an array of size n stored in memory. The selection sort algorithm first selects the smallest element in the array x and place it at array position 0; then it selects the next smallest element in the array x and place it at array position 1. It simply continues this procedure until it places the biggest element in the last position of the array. We will now present to you an algorithm for selection sort. The array is passed through (n-1) times and the smallest element is placed in its respective position in the array as detailed below: Pass 1: Find the location j of the smallest element in the array x [0], x[1],.... x[n-1], and then interchange x[j] with x[0]. Then x[0] is sorted. Pass 2: Leave the first element and find the location j of the smallest element in the sub-array x[1], x[2],.... x[n-1], and then interchange x[1] with x[j]. Then x[0], x[1] are sorted. Pass 3: Leave the first two elements and find the location j of the smallest element in the sub-array x[2], x[3],.

... x[n-1], and then interchange x[2] with x[j]. Then x[0], x[1], x[2] are sorted. Pass (n-1): Find the location j of the smaller of the elements x[n-2] and x[n-1], and then interchange x[j] and x[n- 2]. Then x[0], x[1],.... x[n-2] are sorted. Of course, during this pass x[n-1] will be the biggest element and so the entire array is sorted. Time Complexity: In general we prefer selection sort in case where the insertion sort or the bubble sort requires exclusive swapping. In spite of superiority of the selection sort over bubble sort and the insertion sort (there is significant decrease in run time), its efficiency is also O(n^2 ) for n data items. Example: Let us consider the following example with 9 elements to analyze selection Sort: 1 2 3 4 5 6 7 8 9 Remarks 65 70 75 80 50 60 55 85 45 find the first smallest element i j swap a[i] & a[j] 45 70 75 80 50 60 55 85 65 find the second smallest element i j swap a[i] and a[j] 45 50 75 80 70 60 55 85 65 Find the third smallest element i j swap a[i] and a[j]

45 50 55 80 70 60 75 85 65 Find the fourth smallest element i j swap a[i] and a[j] 45 50 55 60 70 80 75 85 65 Find the fifth smallest element i j swap a[i] and a[j] 45 50 55 60 65 80 75 85 70 Find the sixth smallest element i j swap a[i] and a[j] 45 50 55 60 65 70 75 85 80 Find the seventh smallest element i j swap a[i] and a[j] 45 50 55 60 65 70 75 85 80 Find the eighth smallest element i J swap a[i] and a[j] 45 50 55 60 65 70 75 80 85 The outer loop ends. Non-recursive Program for selection sort:

include

include

void selectionSort( int low, int high ); int a[25]; int main() { int num, i= 0; clrscr(); printf( "Enter the number of elements: " ); scanf("%d", &num); printf( "\nEnter the elements:\n" ); for(i=0; i < num; i++) scanf( "%d", &a[i] ); selectionSort( 0, num - 1 ); printf( "\nThe elements after sorting are: " ); for( i=0; i< num; i++ ) printf( "%d ", a[i] ); return 0; } void selectionSort( int low, int high ) { int i=0, j=0, temp=0, minindex; for( i=low; i <= high; i++ ) { minindex = i; for( j=i+1; j <= high; j++ ) if( a[j] < a[minindex] ) minindex = j; temp = a[i]; a[i] = a[minindex]; a[minindex] = temp; } } Recursive Program for selection sort: #include

Proc e d u r e INSERTIO N S O R T (A, N) // A is the arr ay cont ai ni n g the list of dat a items // N is the num b e r of data items in the list Last ß N – 1 Repe a t For Pass = 1 to Last Step 1 Repe a t For I = 0 to Pass – 1 Step 1 If A[Pass] < A[I] Then Temp ß A[Pass] Repe a t For J = Pass -1 to I Step - A[J +1] ß A[J] End Repe a t A[I] ß Temp End If End Repe a t End Repe a t End INSERTION SORT In Inser tio n Sort algorit h m , Last is mad e to point to the last elem e n t in the list and Pass is mad e to point to the secon d elem e n t in the list. In every pass the Pass is incre m e n t e d to point to the next elem e n t and is contin u e d till it reac h e s the last elem e n t. During eac h pas s A[Pass] is comp a r e d all elem e n t s before it. If A[Pass] is lesse r than A[I] in the list, then A[Pass] is inser t e d in position I. Finally, a sort e d list is obtain e d. For perfor mi n g the inser tion oper a tio n, a variable tem p is used to safely store A[Pass] in it and the n shift right elem e n t s star tin g from A[I] to A[Pass- 1]. Exa m p l e : N = 10 à Num b e r of elem e n t s in the list L à Last P à Pass i = 0 i = 1 i = 2 i = 3 i = 4 i = 5 i = 6 i = 7 i = 8 i = 9 42 23 74 11 65 58 94 36 99 87 P=1 A[P] < A[0] à Insert A[P] at 0 L= 23 42 74 11 65 58 94 36 99 87 P=2 L= A[P] is great e r than all ele m e n t s before it. Henc e No Chang e

P=3 A[P] < A[0] à Insert A[P] at 0 L= 11 23 42 74 65 58 94 36 99 87 P=4 L= A[P] < A[3] à Insert A[P] at 3 11 23 42 65 74 58 94 36 99 87 P=5 L= A[P] < A[3] à Insert A[P] at 3 11 23 42 58 65 74 94 36 99 87 P=6 L= A[P] is great e r than all ele m e n t s before it. Henc e No Chang e 11 23 42 58 65 74 94 36 99 87 P=7 L= A[P] < A[2] à Insert A[P] at 2 11 23 36 42 58 65 74 94 99 87 P=8 L= A[P] is great e r than all ele m e n t s before it. Henc e No Chang e 11 23 36 42 58 65 74 94 99 87 P, L= A[P] < A[7] à Insert A[P] at 7 Sort e d List: 11 23 36 42 58 65 74 87 94 99 Pro g r a m : void arr ay::so r t() { int tem p, last = c o u n t- 1; for (int pass = 1 ; pass < = l a s t ; p a s s + + ) { for (int i=0; i