{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Lecture20

# Lecture20 - ECS 30 Introduction to Programming and Problem...

This preview shows pages 1–8. Sign up to view the full content.

ECS 30 Introduction to Programming and Problem Solving François Gygi Department of Computer Science

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Lecture 20 Chapter 8 Complexity of algorithms: sorting Using multidimensional arrays
bubble sort implementation int ordered = 0; while (!ordered) { int restart = 0; for ( i=0; i<n-1 && !restart; i++ ) { if ( x[i] > x[i+1] ) { swap(&x[i],&x[i+1]); restart = 1; } else if ( i == n-2 ) ordered = 1; } } program bubble.c

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
int x[5] = { 11, 7, 3, 4, 9 }; swap(&x[0],&x[2]); /* { 3, 7, 11, 4, 9 } */ swap(&x[1],&x[3]); /* { 3, 4, 11, 7, 9 } */ swap(&x[2],&x[3]); /* { 3, 4, 7, 11, 9 } */ swap(&x[3],&x[4]); /* { 3, 4, 7, 9, 11 } */ /* done */ Selection sort: search for smallest element and swap
selection sort implementation int get_min(int[] a, int first, int last); { int i, i_small=first, small=a[first]; for ( i=first; i<=last; i++ ) if ( a[i] < small ) { small = a[i]; i_small = i; } return i_small; }

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
selection sort implementation int i, i_min; for ( i=0; i<n-1; i++ ) { /* find position of the smallest element in [i,n-1] */ i_min = get_min(x,i,n-1); if ( i_min != i ) swap(&x[i],&x[i_min]); }
Searching: Finding an element in an array int x[5]; int target_val = 3; int i = 0, found = 0; while ( i < n && !found ) { found = (x[i++] == target_val); } program search.c

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}