CSC Data Structures, Fall, 2009

Size: px
Start display at page:

Download "CSC Data Structures, Fall, 2009"

Transcription

1 An example of using gdb. CSC Data Structures, Fall, 2009 Dr. Dale E. Parson, parson@kutztown.edu, Below are listings for files timesort.cxx and queueofints.h from our sorting assignment. I have planted a bug at lines 55 and 60 of queueofints.h. First I will blow this up and debug the core file created by the fault on bill. Then I will debug the running process in order to illustrate breakpoints. PART 1: Debugging a core dump from an exploding process. Run the program. -bash-3.00$ gmake clean build test_merge /bin/rm -f *.o *.class.jar core *.exe *.obj *.pyc /bin/rm -f timesort timesort.out timesort.dif /bin/bash -c "g++ -c -I. -g StringToInteger.cxx -o StringToInteger.o" /bin/bash -c "g++ -c -I. -g timesort.cxx -o timesort.o" g++ StringToInteger.o timesort.o -o timesort./timesort merge Generating integers Start timer and sort using mergesort. gmake: *** [test_merge] Debug the core file. Use where to see where execution blew up, print to print variable bindings, l ( list ) to list the program, and up and down to navigate up and down the call stack to calling and called functions made visible by where. -bash-3.00$ gdb./timesort core GNU gdb (startup messages) Loaded symbols for /lib/ld.so.1 Core was generated by `./timesort merge '. Program terminated with signal 11, Segmentation fault. #0 0x00013ec4 in queueofints::peek (this=0xffbff7ac, isvalid=@0xffbff6a7) at queueofints.h:68 68 result = buffer[head]; (gdb) where #0 0x00013ec4 in queueofints::peek (this=0xffbff7ac, isvalid=@0xffbff6a7) at queueofints.h:68 #1 0x000135cc in mergephase (merger=@0xffbff7c8, splitter=0xffbff798, runlen=2) at timesort.cxx:386 #2 0x000137e4 in mergesort (merger=@0xffbff7c8, splitter=0xffbff798) at timesort.cxx:416 #3 0x in imergesort (iarray=0x25780, left=0, right= ) at timesort.cxx:437 #4 0x in main (argc=4, argv=0xffbff914) at timesort.cxx:137 (gdb) print head $1 = (gdb) print count $2 = (gdb) print *this $3 = {buffer = 0xf67b90, Capacity = , count = , tail = 0, head = } (gdb) l 63 } 64 int peek(bool &isvalid) { 65 int result = 0 ; 66 isvalid = false ; 67 if (count > 0) { 68 result = buffer[head]; 69 isvalid = true ; 70 } 71 return result ; 72 } (gdb) You can see that the program is blowing up at line 68: result = buffer[head]; and that a head value of exceeds the queue s array capacity of The next logical thing is to look at the places in the code where the head field is adjusted, and try to determine why it gets set to a value greater than capacity. You may be able to reason that out without the debugger. We will use the debugger on a smaller array to be sorted instead. Before doing that, let s look at the up and down commands for inspecting the stack frames of calling function. (gdb) where #0 0x00013ec4 in queueofints::peek (this=0xffbff7ac, isvalid=@0xffbff6a7) at queueofints.h:68 #1 0x000135cc in mergephase (merger=@0xffbff7c8, splitter=0xffbff798, runlen=2) at timesort.cxx:386 #2 0x000137e4 in mergesort (merger=@0xffbff7c8, splitter=0xffbff798) at timesort.cxx:416 #3 0x in imergesort (iarray=0x25780, left=0, right= ) at timesort.cxx:437 #4 0x in main (argc=4, argv=0xffbff914) at timesort.cxx:137 (gdb) up #1 0x000135cc in mergephase (merger=@0xffbff7c8, splitter=0xffbff798, runlen=2) at timesort.cxx: int v1 = splitter[1].peek(ignoreme); (gdb) list 381 int srl[2] ; // remaining run lengths for each queue 382 srl[0] = runlen ; // both sides have contents, [0] is a full run 383 srl[1] = (splitter[1].size() < runlen)? splitter[1].size() : runlen ; 384 while (srl[0] > 0 && srl[1] > 0) { page 1 page 2

2 385 int v0 = splitter[0].peek(ignoreme); 386 int v1 = splitter[1].peek(ignoreme); 387 if (v0 <= v1) { 388 merger.enqueue(v0); 389 splitter[0].dequeue(); 390 srl[0] -= 1 ; (gdb) print v0 $4 = 645 (gdb) print v1 $5 = 0 (gdb) up #2 0x000137e4 in mergesort (merger=@0xffbff7c8, splitter=0xffbff798) at timesort.cxx: mergephase(merger, splitter, runlen); (gdb) print merger $6 = (queueofints {buffer = 0x25780, Capacity = , count = , tail = , head = } (gdb) print splitter $7 = (queueofints *) 0xffbff798 (gdb) print splitter[0] $8 = {buffer = 0x7c6988, Capacity = , count = , tail = 0, head = } (gdb) print splitter[1] $9 = {buffer = 0xf67b90, Capacity = , count = , tail = 0, head = } (gdb) down 2 #0 0x00013ec4 in queueofints::peek (this=0xffbff7ac, isvalid=@0xffbff6a7) at queueofints.h:68 68 result = buffer[head]; (gdb) quit Now we will run the process within the debugger using a smaller array. You can run the test using gmake to see what the command line looks like, and then adapt that to starting the process with gdb using the --args command line option. First run the command line using a smaller array to see whether the bug still appears, and then use gdb. -bash-3.00$ gmake clean build test_merge /bin/rm -f *.o *.class.jar core *.exe *.obj *.pyc /bin/rm -f timesort timesort.out timesort.dif /bin/bash -c "g++ -c -I. -g StringToInteger.cxx -o StringToInteger.o" /bin/bash -c "g++ -c -I. -g timesort.cxx -o timesort.o" g++ StringToInteger.o timesort.o -o timesort./timesort merge Generating integers Start timer and sort using mergesort. gmake: *** [test_merge] -bash-3.00$./timesort merge Generating integers Start timer and sort using mergesort. -bash-3.00$./timesort merge 20 1 Generating 20 integers. Start timer and sort using mergesort. -bash-3.00$./timesort merge Generating 2000 integers. Start timer and sort using mergesort. -bash-3.00$./timesort merge Generating 200 integers. Start timer and sort using mergesort. -bash-3.00$./timesort merge Generating 1000 integers. Start timer and sort using mergesort. -bash-3.00$./timesort merge Generating 500 integers. Start timer and sort using mergesort. -bash-3.00$./timesort merge Generating 250 integers. Start timer and sort using mergesort. -bash-3.00$./timesort merge Generating 275 integers. Start timer and sort using mergesort. -bash-3.00$./timesort merge Generating 375 integers. Start timer and sort using mergesort. -bash-3.00$./timesort merge Generating 300 integers. Start timer and sort using mergesort. -bash-3.00$./timesort merge Generating 325 integers. Start timer and sort using mergesort. -bash-3.00$./timesort merge Generating 350 integers. Start timer and sort using mergesort. An arrays size of 250 does the job. Here is how to run that process using gdb. -bash-3.00$ gdb --args./timesort merge GNU gdb This GDB was configured as "sparc-sun-solaris2.8"... (gdb) break main Breakpoint 1 at 0x11a38: file timesort.cxx, line 66. (gdb) run Starting program: /export/home/faculty/parson/private/csc237/timesort/timesort merge warning: Temporarily disabling breakpoints for unloaded shared library "/usr/lib/ld.so.1" page 3 page 4

3 Breakpoint 1, main (argc=4, argv=0xffbff8fc) at timesort.cxx:66 66 bool isbinarysearch = false, isprint = false ; I usually set any additional breakpoints of interest after setting a breakpoint at function main, and running the program until it hits that breakpoint. Sometimes if you set breakpoints before starting program execution, then the breakpoints do not work due to how UNIX processes load dynmaic code libraries. A gdb use can set breakpoints by saying: break FUNCTIONAME (for regular C functions) break CLASS::FUNCTIONNAME(for member functions of classes) break FILE:LINENUMBER (to break in the middle of a function) You can even add a condition to a breakpoint. (gdb) help break Set breakpoint at specified line or function. break [LOCATION] [thread THREADNUM] [if CONDITION] LOCATION may be a line number, function name, or "*" and an address. If a line number is specified, break at start of code for that line. If a function is specified, break at start of code for that function. If an address is specified, break at that exact address. With no LOCATION, uses current execution address of selected stack frame. This is useful for breaking on return to a stack frame. THREADNUM is the number from "info threads". CONDITION is a boolean expression. Multiple breakpoints at one place are permitted, and useful if conditional. Do "help breakpoints" for info on other commands dealing with breakpoints. (gdb) help breakpoints Making program stop at certain points. List of commands: awatch -- Set a watchpoint for an expression break -- Set breakpoint at specified line or function catch -- Set catchpoints to catch events clear -- Clear breakpoint at specified line or function commands -- Set commands to be executed when a breakpoint is hit condition -- Specify breakpoint number N to break only if COND is true delete -- Delete some breakpoints or auto-display expressions delete breakpoints -- Delete some breakpoints or auto-display expressions delete display -- Cancel some expressions to be displayed when program stops delete mem -- Delete memory region delete tracepoints -- Delete specified tracepoints disable -- Disable some breakpoints disable breakpoints -- Disable some breakpoints disable display -- Disable some expressions to be displayed when program stops disable mem -- Disable memory region disable tracepoints -- Disable specified tracepoints enable -- Enable some breakpoints enable delete -- Enable breakpoints and delete when hit enable display -- Enable some expressions to be displayed when program stops enable mem -- Enable memory region enable once -- Enable breakpoints for one hit enable tracepoints -- Enable specified tracepoints hbreak -- Set a hardware assisted breakpoint ignore -- Set ignore-count of breakpoint number N to COUNT rbreak -- Set a breakpoint for all functions matching REGEXP rwatch -- Set a read watchpoint for an expression tbreak -- Set a temporary breakpoint tcatch -- Set temporary catchpoints to catch events thbreak -- Set a temporary hardware assisted breakpoint watch -- Set a watchpoint for an expression Type "help" followed by command name for full documentation. Type "apropos word" to search for commands related to "word". Command name abbreviations are allowed if unambiguous. Since I know from debugging the core file that head is being set to a value > capacity, I will look for every place that head is set to a new value, and set a conditional breakpoint that triggers only if head > capacity. The only place that head is adjusted in this program is queueofints.h:55 so we start out by setting an unconditional breakpoint there. (gdb) break queueofints.h:55 Breakpoint 2 at 0x13d94: file queueofints.h, line 55. (gdb) cont Continuing. Generating 350 integers. Start timer and sort using mergesort. Breakpoint 2, queueofints::dequeue (this=0xffbff7b0) at queueofints.h:55 55 head = (head + 1) ; // THIS IS A BUG THAT WE WILL DEBUG WITH GDB You can use print to print out variable values, step to move forward one line at a time and also to call into functions or return from functions, and next to step over functions instead of going into them. Breakpoint 2, queueofints::dequeue (this=0xffbff7b0) at queueofints.h:55 55 head = (head + 1) ; // THIS IS A BUG THAT WE WILL DEBUG WITH GDB (gdb) print head $1 = 0 56 count-- ; page 5 page 6

4 (gdb) print head $2 = 1 (gdb) print count $3 = result = true ; (gdb) print count $4 = return result ; 63 } splitphase (merger=@0xffbff7b0, splitter=0xffbff780, runlen=1) at timesort.cxx: rl-- ; (gdb) It clearly will take a long time to get head up past capacity, so disable breakpoint 2 and set a new, conditional breakpoint. (gdb) break queueofints.h:56 if head >= Capacity Breakpoint 4 at 0x13da8: file queueofints.h, line 56. (gdb) cont Continuing. Breakpoint 4, queueofints::dequeue (this=0xffbff7b0) at queueofints.h:56 56 count-- ; (gdb) print head $7 = 350 (gdb) print Capacity $8 = 350 At this point you can probably figure out the cause of the bug. Typically a subset of the above gdb commands will be enough to allow you to debug any C++ program. Using gdb requires practice. 1 /** Taken from midterm237fall08.cxx 2 queueofints.h, a circular queue of ints, adapted from the CSC 237 midterm. 3 Dr. Dale Parson, Fall, */ 6 #include <iostream> 7 using namespace std ; 8 9 // Problem 1: 10 class queueofints { // fixed size circular queue class 11 private: 12 int *buffer ; // buffer for a circular queue 13 int Capacity ; // number of element slots available in buffer 14 int count ; // number of elements in queue 15 int tail ; // where to enqueue an element 16 int head ; // where to dequeue an element 17 public: 18 queueofints(int *Iarray, int Capacity, int Size) { 19 // STUDENTS NEED ONLY TO WRITE THE CONSTRUCTOR. 20 // THERE ARE NO OTHER CHANGES. 21 buffer = Iarray ; 22 this->capacity = Capacity ; 23 count = Size ; 24 // watch out for (Size % Capacity) when Capacity == 0, divides by 0! 25 tail = (Size == Capacity)? 0 : Size ; 26 head = 0 ; } 29 ~queueofints() { 30 } void printqueue() { 33 int hd = head, ct = count ; 34 while (ct > 0) { 35 cout << buffer[hd]; 36 hd = (hd + 1) % Capacity ; 37 ct-- ; 38 } 39 } bool enqueue(int value) { 42 bool result = false ; 43 if (count < Capacity) { 44 buffer[tail] = value; 45 tail = (tail + 1) % Capacity ; // wraps tail around to 0 46 count++ ; 47 result = true ; 48 } 49 return result ; 50 } 51 bool dequeue() { 52 bool result = false ; 53 if (count > 0) { 54 // head = (head + 1) % Capacity ; // wraps head around to 0 55 head = (head + 1) ; // THIS IS A BUG THAT WE WILL DEBUG WITH GDB 56 count-- ; 57 result = true ; 58 } 59 if (count == 0) { // THIS LINE WAS ADDED FOR MERGESORT TO WORK. page 7 page 8

5 WHY??? 60 // ANOTHER BUG head = tail = 0 ; 61 } 62 return result ; 63 } 64 int peek(bool &isvalid) { 65 int result = 0 ; 66 isvalid = false ; 67 if (count > 0) { 68 result = buffer[head]; 69 isvalid = true ; 70 } 71 return result ; 72 } 73 int size() { 74 return count ; 75 } 76 int capacity () { 77 return Capacity ; 78 } 79 } ; 1 /* timesort.cxx -- A test driver of various sorts & binary search. 2 3 CSC237, Fall, 2009, Dr. Dale Parson. 4 */ 5 6 // THE FOLLOWING EXIT CODES CONSTITUTE THE RETURN VALUES FROM MAIN: 7 static const int SUCCESS = 0 ; /* successful program execution */ 8 static const int PARMERR = 1 ; /* invalid command line values */ 9 10 #include <stdlib.h> 11 #include <sys/times.h> 12 #include <limits.h> #include <iostream> 15 #include StringToInteger.h 16 using namespace std ; 17 #include queueofints.h typedef void (*sortfunction)(int iarray[], int left, int right); 20 static void printarray(char *prompt, int iarray[], int numelems) ; 21 static void quicksort(int iarray[], int left, int right); 22 static void insertionsort(int iarray[], int left, int right); 23 static void selectionsort(int iarray[], int left, int right); 24 static void bubblesort(int iarray[], int left, int right); 25 static void radixsort(int iarray[], int left, int right); 26 static void imergesort(int iarray[], int left, int right); // BINARY SEARCH 29 static int * binsearch(int *iptr, int count, int key) { 30 if (count < 1 (count == 1 && iptr[0]!= key) 31 key < iptr[0] key > iptr[count-1]) { 32 return NULL ; 33 } else if (count == 1) { 34 return iptr ; 35 } else { 36 int half = count / 2 ; 37 if (key <= iptr[half-1]) { 38 return binsearch(iptr,half,key); 39 } else { 40 return binsearch(iptr+half,count-half, key); 41 } 42 } 43 } static const char *usage = 46 usage: timesort quick insertion selection bubble radix merge NUMELEMS SEED [ BP ] ; /* 49 Function: main main is a test driver that exercises implementations of 52 a timed named sort and binary search Parameters: See usage documentation above Exit value: SUCCESS is argv is OK, else PARMERR */ 61 int *intarray ; 62 int 63 main(const int argc, char *argv[]) { 64 int size, seed ; 65 bool validflag ; 66 bool isbinarysearch = false, isprint = false ; 67 sortfunction sortfunc = NULL ; 68 struct tms before, after ; 69 if (argc!= 4) { 70 if (argc == 5) { 71 // BP or PB or just P or B in last command line argument give 72 // true flags for binasry search(b) and print the array (P). page 9 page 10

6 73 if (*(argv[4]) == B *(argv[4]+1) == B ) { 74 isbinarysearch = true ; 75 } 76 if (*(argv[4]) == P *(argv[4]+1) == P ) { 77 isprint = true ; 78 } 79 if (! (isbinarysearch isprint)) { 80 // argv[4] is no good. 81 cerr << Invalid final command line argument, 82 << must be B and/or P: << argv[4] << endl ; 83 cerr << usage << endl ; 84 exit(parmerr); 85 } 86 } else { 87 cerr << usage << endl ; 88 exit(parmerr); 89 } 90 } 91 size = StringToInteger(argv[2], validflag); 92 if ((! validflag) size < 0) { 93 cerr << Invalid size: << argv[2] << endl ; 94 cerr << usage << endl ; 95 exit(parmerr); 96 } 97 seed = StringToInteger(argv[3], validflag); 98 if (! validflag) { 99 cerr << Invalid random number seed: << argv[3] << endl ; 100 cerr << usage << endl ; 101 exit(parmerr); 102 } 103 if (strcmp(argv[1], quick ) == 0) { 104 sortfunc = quicksort ; 105 } else if (strcmp(argv[1], insertion ) == 0) { 106 sortfunc = insertionsort ; 107 } else if (strcmp(argv[1], selection ) == 0) { 108 sortfunc = selectionsort ; 109 } else if (strcmp(argv[1], bubble ) == 0) { 110 sortfunc = bubblesort ; 111 } else if (strcmp(argv[1], radix ) == 0) { 112 sortfunc = radixsort ; 113 } else if (strcmp(argv[1], merge ) == 0) { 114 sortfunc = imergesort ; 115 } else { 116 cerr << Invalid sort function name: << argv[1] << endl ; 117 cerr << usage << endl ; 118 exit(parmerr); 119 } 120 srand(seed); 121 intarray = new int [ size ]; 122 cout << Generating << size << integers ; 123 cout.flush(); 124 for (int i = 0 ; i < size ; i++) { 125 if ((i & 0x0ffff) == 0) { // every print a. 126 cout <<. ; 127 cout.flush(); 128 } 129 intarray[i] = rand(); 130 } 131 if (isprint) { 132 cout << \nbefore SORTING: << endl << endl ; 133 printarray(argv[1], intarray, size); 134 } 135 cout << Start timer and sort using << argv[1] << sort. << endl ; 136 times(&before); 137 (*sortfunc)(intarray,0,size-1); 138 times(&after); 139 cout << User CPU time = 140 << ((after.tms_utime - before.tms_utime) / (double)clk_tck) 141 << secs, system CPU time = 142 << ((after.tms_stime - before.tms_stime) / (double)clk_tck) 143 << secs. << endl ; 144 if (isprint) { 145 cout << \nafter SORTING: << endl << endl ; 146 printarray(argv[1], intarray, size); 147 } 148 if (isbinarysearch) { 149 int key ; 150 cout << Enter search key: ; 151 cout.flush(); 152 cin >> key ; 153 while (! cin.eof()) { // Hit ctrl-c to break out 154 int *loc = binsearch(intarray, size, key); 155 if (loc == NULL) { 156 cout << Key << key << not found in array. << endl ; 157 } else { 158 cout << Key << key << found at array index 159 << loc - intarray <<. << endl ; 160 } 161 cout << endl << Enter search key: ; 162 cout.flush(); 163 cin >> key ; 164 } 165 cout << endl ; 166 } 167 return(success); 168 } page 11 page 12

7 static void printarray(char *prompt, int iarray[], int numelems) { 171 cout << prompt << \n ; 172 for (int i = 0 ; i < numelems ; i++) { 173 cout << iarray[i] << endl ; 174 } 175 } // If there are at least 3 elements, pick a value that is >= one 178 // of them and <= the other as the pivot. This decreases the probability 179 // of hitting a degenerate case where all or almost all elements partition 180 // to one side of the pivot. 181 // The return value is the pivot, also swapped into iarray[left]. 182 static int pickpivot(int iarray[], int left, int right) { 183 int result ; 184 int count = right - left + 1 ; 185 int mid = (left + right) / 2 ; 186 if (count < 3) { 187 result = iarray[left]; // [1] element or 50/50 odds for [2] 188 } else if ((iarray[mid] <= iarray[left] && iarray[left] <= iarray[right]) 189 (iarray[right] <= iarray[left] && iarray[left] <= iarray[mid])){ 190 result = iarray[left]; 191 } else if ((iarray[left] <= iarray[mid] && iarray[mid] <= iarray[right]) 192 (iarray[right] <= iarray[mid] && iarray[mid] <= iarray[left])){ 193 result = iarray[mid] ; 194 iarray[mid] = iarray[left] ; 195 iarray[left] = result ; 196 } else if ((iarray[mid] <= iarray[right] && iarray[right] <= iarray[left]) 197 (iarray[left] <= iarray[right] && iarray[right] <= iarray[mid])){ 198 result = iarray[right] ; 199 iarray[right] = iarray[left] ; 200 iarray[left] = result ; 201 } 202 return result ; 203 } // partition is a helper function for quicksort(). 206 // partition partitions an array into a left half and a right half, 207 // where all values in the left half or <= some pivot value, and 208 // all values in the right half are > that pivot value. 209 // partition may not divide the array exactly in half; left and right 210 // part would be a better term. 211 // RETURN index of the element around which the array is partitioned. 212 static int partition(int iarray[], int left, int right) { 213 int pivot = pickpivot(iarray, left, right); 214 int low = left + 1 ; // scan up looking for a too-high value 215 int high = right ; // scan down looking for a too-low value while (low < high) { // scan from both sides of array 218 while (low <= high && iarray[low] <= pivot) { // in correct side 219 low++; 220 } 221 while (low <= high && iarray[high] > pivot) { // in correct side 222 high--; 223 } 224 // If there are two elements on the wrong side, swap them. 225 if (low < high) { 226 int temp = iarray[high]; 227 iarray[high] = iarray[low]; 228 iarray[low] = temp ; 229 } 230 } 231 // We still need to place the pivot in the correct spot. 232 while (high > left && iarray[high] >= pivot) { 233 high--; 234 } 235 // swap pivot with a lower value if there is one 236 if (pivot > iarray[high]) { 237 iarray[left] = iarray[high]; 238 iarray[high] = pivot ; 239 return high; 240 } else { 241 return left ; 242 } 243 } // #define VERBOSE 246 #ifdef VERBOSE 247 // Implement the quick sort algorithm. 248 static void quicksort(int iarray[], int left, int right) { 249 static int depth = 0 ; 250 depth++ ; // used only to report recursion depth 251 if (left < right) { 252 // 1. Partition array so all values <= iarray[pivotlocation] of left 253 // of pivotlocation, and all values > pivotlocation are right of it. 254 int pivotlocation = partition(iarray, left, right); 255 // Sort the left partition. 256 cout << DEPTH << depth <<, PARTITION pivot value = 257 << iarray[pivotlocation] << AT INDEX << pivotlocation << endl ; 258 quicksort(iarray, left, pivotlocation-1); 259 cout << DEPTH << depth << ; 260 printarray( LEFT SORTED, iarray+left, pivotlocation-left); 261 // Sort the right partition. 262 quicksort(iarray, pivotlocation+1, right); 263 cout << DEPTH << depth << ; 264 printarray( RIGHT SORTED, page 13 page 14

8 265 iarray+pivotlocation+1, right-pivotlocation); 266 } 267 depth--; 268 } 269 #else 270 // Implement the quick sort algorithm. 271 static void quicksort(int iarray[], int left, int right) { 272 if (left < right) { 273 // 1. Partition array so all values <= iarray[pivotlocation] are left 274 // of pivotlocation, and all values > pivotlocation are right of it. 275 int pivotlocation = partition(iarray, left, right); 276 // Sort the left partition. 277 quicksort(iarray, left, pivotlocation-1); 278 // Sort the right partition. 279 quicksort(iarray, pivotlocation+1, right); 280 } 281 } 282 #endif static void insertionsort(int iarray[], int left, int right){ 285 // Grow the sorted left subarray by insertion of 1 at each step. 286 for (int uninsertedix = left+1 ; uninsertedix <= right ; uninsertedix++) { 287 int insvalue = iarray[uninsertedix]; 288 for (int dest = left ; dest < uninsertedix ; dest++) { 289 if (insvalue < iarray[dest]) { 290 for (int shift = uninsertedix ; shift > dest ; shift--) { 291 iarray[shift] = iarray[shift-1]; 292 } 293 iarray[dest] = insvalue ; 294 break ; 295 } 296 } 297 } 298 } static void selectionsort(int iarray[], int left, int right){ 301 for (int selix = left ; selix < right ; selix++) { 302 // Select value for slot selix. 303 int smallvalix = selix ; 304 // Search ahead in array for correct value. 305 for (int otherix = selix+1 ; otherix <= right ; otherix++) { 306 if (iarray[otherix] < iarray[smallvalix]) { 307 smallvalix = otherix ; 308 } 309 } 310 if (smallvalix!= selix) { 311 int tmp = iarray[selix]; 312 iarray[selix] = iarray[smallvalix]; 313 iarray[smallvalix] = tmp ; 314 } 315 } 316 } static void bubblesort(int iarray[], int left, int right){ 319 // Taken from textbook, page bool sorted = false ; // reset to false whenever a swap occurs 321 int size = right - left + 1 ; 322 for (int pass = 1 ; (pass < size) && (! sorted) ; pass++) { 323 // bubble the highest value to the end, if no swap occurs we re done 324 sorted = true ; 325 for (int ix = left ; ix <= right-pass ; ix++) { 326 if (iarray[ix] > iarray[ix+1]) { 327 int tmp = iarray[ix+1] ; 328 iarray[ix+1] = iarray[ix]; 329 iarray[ix] = tmp ; 330 sorted = false ; // We did not go through cleanly. 331 } 332 } 333 } 334 } static void radixsort(int iarray[], int left, int right) { 337 static int bitsinbyte = 8 ; 338 static int numbits = sizeof(int) * bitsinbyte ; 339 int size = right - left + 1 ; 340 int *binarray = new int [ 2 * size ]; 341 for (int i = 0, mask = 1 ; i < numbits ; i++, mask = mask << 1) { 342 int count[2] ; 343 count[0] = count[1] = 0 ; 344 for (int j = left ; j <= right ; j++) { 345 int bin = (iarray[j] & mask) >> i ; 346 binarray[bin * size + count[bin]] = iarray[j] ; 347 count[bin] = count[bin] + 1 ; 348 } 349 int restoreix = 0 ; 350 for (int bin = 0 ; bin < 2 ; bin++) { 351 for (int j = 0 ; j < count[bin] ; j++) { 352 iarray[restoreix++] = binarray[bin * size + j]; 353 } 354 } 355 } 356 delete [] binarray ; 357 } // This is the mergesort s splitphase for the assignment. 360 static void splitphase(queueofints &merger, queueofints splitter[2], page 15 page 16

9 361 int runlen) { 362 bool ignoreme ; // We only peek on queues with data, etc. 363 int qid = 0 ; 364 while (merger.size() > 0) { // while there are still runs to split ; 365 int rl = (merger.size() < runlen)? merger.size() : runlen ; 366 while (rl > 0) { 367 splitter[qid].enqueue(merger.peek(ignoreme)); 368 merger.dequeue(); 369 rl-- ; 370 } 371 qid = qid ^ 1 ; // switch to other splitter 372 } 373 } // This is the mergesort s mergephase for the assignment. 376 void mergephase(queueofints &merger, queueofints splitter[2], 377 int runlen) { 378 bool ignoreme ; 379 int qtodrain ; // The queue to drain when 1 runs ends, 380 while (splitter[0].size() > 0 && splitter[1].size() > 0) { 381 int srl[2] ; // remaining run lengths for each queue 382 srl[0] = runlen ; // both sides have contents, [0] is a full run 383 srl[1] = (splitter[1].size() < runlen)? splitter[1].size() : runlen ; 384 while (srl[0] > 0 && srl[1] > 0) { 385 int v0 = splitter[0].peek(ignoreme); 386 int v1 = splitter[1].peek(ignoreme); 387 if (v0 <= v1) { 388 merger.enqueue(v0); 389 splitter[0].dequeue(); 390 srl[0] -= 1 ; 391 } else { // v1 is less 392 merger.enqueue(v1); 393 splitter[1].dequeue(); 394 srl[1] -= 1 ; 395 } 396 } 397 int qtodrain = (srl[0] > 0)? 0 : 1 ; 398 while (srl[qtodrain] > 0) { 399 merger.enqueue(splitter[qtodrain].peek(ignoreme)); 400 splitter[qtodrain].dequeue(); 401 srl[qtodrain] -= 1 ; 402 } 403 } 404 // splitter[0] may have a leftover run or partial run 405 while (splitter[0].size() > 0) { 406 merger.enqueue(splitter[0].peek(ignoreme)); 407 splitter[0].dequeue(); 408 } 409 } // This is the function specified for the assignment. 412 void mergesort(queueofints &merger, queueofints splitter[2]) { 413 int runlen = 1 ; 414 while (runlen < merger.size()) { 415 splitphase(merger, splitter, runlen); 416 mergephase(merger, splitter, runlen); 417 runlen *= 2 ; 418 } 419 } // This function has the same signature as the other sorts above. 422 // It prepares arguments for the function as spec d by the assignment. 423 void imergesort(int *iarray, int left, int right) { 424 if (iarray == NULL left > right) { 425 // Don t try to do pointer arithemtic on a NULL pointer. 426 return ; 427 } 428 int *arraytosort = iarray + left ; 429 int count = right - left + 1 ; 430 queueofints merger(arraytosort, count, count); 431 int *aisle0 = new int [ count ]; // Like an aisle in the classroom. 432 int *aisle1 = new int [ count/2 ]; // Never more than 1/2 the elements. 433 queueofints splitter[] = { 434 queueofints(aisle0, count, 0), 435 queueofints(aisle1, count/2, 0) 436 }; 437 mergesort(merger, splitter); 438 delete [] aisle0 ; 439 delete [] aisle1 ; 440 } page 17 page 18

GDB Linux GNU Linux Distribution. gdb gcc g++ -g gdb EB_01.cpp

GDB Linux GNU Linux Distribution. gdb gcc g++ -g gdb EB_01.cpp B Linux GDB GDB Linux GNU GPL Linux Distribution Linux E-B.1 gcc g++ -g EB_01.cpp EB_01.cpp E/EB/EB_01.cpp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 /**** :EB_01.cpp : *****/ #include

More information

Program Design: Using the Debugger

Program Design: Using the Debugger rogram Design, February 2, 2004 1 Program Design: Using the Debugger A debugger is an alternative to putting print (printf in C) statements in your program, recompiling and trying to find out what values

More information

Chapter 10 - Notes Applications of Arrays

Chapter 10 - Notes Applications of Arrays Chapter - Notes Applications of Arrays I. List Processing A. Definition: List - A set of values of the same data type. B. Lists and Arrays 1. A convenient way to store a list is in an array, probably a

More information

Linked List using a Sentinel

Linked List using a Sentinel Linked List using a Sentinel Linked List.h / Linked List.h Using a sentinel for search Created by Enoch Hwang on 2/1/10. Copyright 2010 La Sierra University. All rights reserved. / #include

More information

C++ for Everyone, 2e, Cay Horstmann, Copyright 2012 John Wiley and Sons, Inc. All rights reserved. Using a Debugger WE5.

C++ for Everyone, 2e, Cay Horstmann, Copyright 2012 John Wiley and Sons, Inc. All rights reserved. Using a Debugger WE5. Using a Debugger WE5 W o r k E D E x a m p l e 5.2 Using a Debugger As you have undoubtedly realized by now, computer programs rarely run perfectly the first time. At times, it can be quite frustrating

More information

CSE au Midterm Exam Nov. 2, 2018 Sample Solution

CSE au Midterm Exam Nov. 2, 2018 Sample Solution Question 1. (16 points) Build tools and make. We re building a C++ software back-end prototype for a new food web site. So far, we ve got the following source files with the code for two main programs

More information

Lab 8. Follow along with your TA as they demo GDB. Make sure you understand all of the commands, how and when to use them.

Lab 8. Follow along with your TA as they demo GDB. Make sure you understand all of the commands, how and when to use them. Lab 8 Each lab will begin with a recap of last lab and a brief demonstration by the TAs for the core concepts examined in this lab. As such, this document will not serve to tell you everything the TAs

More information

Using the Xcode Debugger

Using the Xcode Debugger g Using the Xcode Debugger J Objectives In this appendix you ll: Set breakpoints and run a program in the debugger. Use the Continue program execution command to continue execution. Use the Auto window

More information

CS 137 Part 8. Merge Sort, Quick Sort, Binary Search. November 20th, 2017

CS 137 Part 8. Merge Sort, Quick Sort, Binary Search. November 20th, 2017 CS 137 Part 8 Merge Sort, Quick Sort, Binary Search November 20th, 2017 This Week We re going to see two more complicated sorting algorithms that will be our first introduction to O(n log n) sorting algorithms.

More information

Sorting. Task Description. Selection Sort. Should we worry about speed?

Sorting. Task Description. Selection Sort. Should we worry about speed? Sorting Should we worry about speed? Task Description We have an array of n values in any order We need to have the array sorted in ascending or descending order of values 2 Selection Sort Select the smallest

More information

! Search: find a given item in a list, return the. ! Sort: rearrange the items in a list into some. ! list could be: array, linked list, string, etc.

! Search: find a given item in a list, return the. ! Sort: rearrange the items in a list into some. ! list could be: array, linked list, string, etc. Searching & Sorting Week 11 Gaddis: 8, 19.6,19.8 CS 5301 Fall 2014 Jill Seaman 1 Definitions of Search and Sort! Search: find a given item in a list, return the position of the item, or -1 if not found.!

More information

CSCI0330 Intro Computer Systems Doeppner. Lab 02 - Tools Lab. Due: Sunday, September 23, 2018 at 6:00 PM. 1 Introduction 0.

CSCI0330 Intro Computer Systems Doeppner. Lab 02 - Tools Lab. Due: Sunday, September 23, 2018 at 6:00 PM. 1 Introduction 0. CSCI0330 Intro Computer Systems Doeppner Lab 02 - Tools Lab Due: Sunday, September 23, 2018 at 6:00 PM 1 Introduction 0 2 Assignment 0 3 gdb 1 3.1 Setting a Breakpoint 2 3.2 Setting a Watchpoint on Local

More information

KF5008 Algorithm Efficiency; Sorting and Searching Algorithms;

KF5008 Algorithm Efficiency; Sorting and Searching Algorithms; KF5008 Algorithm Efficiency; Sorting and Searching Algorithms; Efficiency: Principles An algorithm is a step-by-step procedure for solving a stated problem. The algorithm will be performed by a processor

More information

LAB #8. GDB can do four main kinds of things (plus other things in support of these) to help you catch bugs in the act:

LAB #8. GDB can do four main kinds of things (plus other things in support of these) to help you catch bugs in the act: LAB #8 Each lab will begin with a brief demonstration by the TAs for the core concepts examined in this lab. As such, this document will not serve to tell you everything the TAs will in the demo. It is

More information

CS125 : Introduction to Computer Science. Lecture Notes #38 and #39 Quicksort. c 2005, 2003, 2002, 2000 Jason Zych

CS125 : Introduction to Computer Science. Lecture Notes #38 and #39 Quicksort. c 2005, 2003, 2002, 2000 Jason Zych CS125 : Introduction to Computer Science Lecture Notes #38 and #39 Quicksort c 2005, 2003, 2002, 2000 Jason Zych 1 Lectures 38 and 39 : Quicksort Quicksort is the best sorting algorithm known which is

More information

Sorting Algorithms. + Analysis of the Sorting Algorithms

Sorting Algorithms. + Analysis of the Sorting Algorithms Sorting Algorithms + Analysis of the Sorting Algorithms Insertion Sort What if first k elements of array are already sorted? 4, 7, 12, 5, 19, 16 We can shift the tail of the sorted elements list down and

More information

CS 310 Advanced Data Structures and Algorithms

CS 310 Advanced Data Structures and Algorithms CS 310 Advanced Data Structures and Algorithms Sorting June 13, 2017 Tong Wang UMass Boston CS 310 June 13, 2017 1 / 42 Sorting One of the most fundamental problems in CS Input: a series of elements with

More information

Bubble sort starts with very first two elements, comparing them to check which one is greater.

Bubble sort starts with very first two elements, comparing them to check which one is greater. Bubble Sorting: Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they

More information

CSC UNIX System, Spring 2015

CSC UNIX System, Spring 2015 ` CSC 352 - UNIX System, Spring 2015 Assignment 2, due by 11:59 on Friday March 6 via gmake turnitin. Dr. Dale E. Parson, http://faculty.kutztown.edu/parson The directory, source-file and makefile contents

More information

LAB #8. Last Survey, I promise!!! Please fill out this really quick survey about paired programming and information about your declared major and CS.

LAB #8. Last Survey, I promise!!! Please fill out this really quick survey about paired programming and information about your declared major and CS. LAB #8 Each lab will begin with a brief demonstration by the TAs for the core concepts examined in this lab. As such, this document will not serve to tell you everything the TAs will in the demo. It is

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 10 October 1, 2018 CPSC 427, Lecture 10, October 1, 2018 1/20 Brackets Example (continued from lecture 8) Stack class Brackets class Main

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

Sorting. CPSC 259: Data Structures and Algorithms for Electrical Engineers. Hassan Khosravi

Sorting. CPSC 259: Data Structures and Algorithms for Electrical Engineers. Hassan Khosravi CPSC 259: Data Structures and Algorithms for Electrical Engineers Sorting Textbook Reference: Thareja first edition: Chapter 14: Pages 586-606 Thareja second edition: Chapter 14: Pages 424-456 Hassan Khosravi

More information

Lab 7 (50 pts) Due Sunday, May 20)

Lab 7 (50 pts) Due Sunday, May 20) Lab 7 (50 pts) Due Sunday, May 20) For this lab, you will be comparing sorting algorithms, specifically the speed of selection, insertion, quick, and merge sort on random, in-order, and reverse-order lists

More information

The University Of Michigan. EECS402 Lecture 07. Andrew M. Morgan. Sorting Arrays. Element Order Of Arrays

The University Of Michigan. EECS402 Lecture 07. Andrew M. Morgan. Sorting Arrays. Element Order Of Arrays The University Of Michigan Lecture 07 Andrew M. Morgan Sorting Arrays Element Order Of Arrays Arrays are called "random-access" data structures This is because any element can be accessed at any time Other

More information

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive) Final Exam Exercises Chapters 1-7 + 11 Write C++ code to: l Determine if a number is odd or even CS 2308 Fall 2016 Jill Seaman l Determine if a number/character is in a range - 1 to 10 (inclusive) - between

More information

About this exam review

About this exam review Final Exam Review About this exam review I ve prepared an outline of the material covered in class May not be totally complete! Exam may ask about things that were covered in class but not in this review

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Discussion 2C Notes (Week 3, January 21) TA: Brian Choi Section Webpage:

Discussion 2C Notes (Week 3, January 21) TA: Brian Choi Section Webpage: Discussion 2C Notes (Week 3, January 21) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs32 Abstraction In Homework 1, you were asked to build a class called Bag. Let

More information

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures The main body and cout Agenda 1 Fundamental data types Declarations and definitions Control structures References, pass-by-value vs pass-by-references The main body and cout 2 C++ IS AN OO EXTENSION OF

More information

CSCI 102L - Data Structures Midterm Exam #2 Spring 2011

CSCI 102L - Data Structures Midterm Exam #2 Spring 2011 CSCI 102L - Data Structures Midterm Exam #2 Spring 2011 (12:30pm - 1:50pm, Thursday, March 24) Instructor: Bill Cheng ( This exam is closed book, closed notes, closed everything. No cheat sheet allowed.

More information

GDB Tutorial. University of Waterloo

GDB Tutorial. University of Waterloo GDB Tutorial University of Waterloo Version 1.0 Caroline Kierstead and Peter A. Buhr c 2002 April 1, 2002 Permission is granted to make copies for personal or educational use 2 GDB Tutorial Contents 1

More information

Overview of Sorting Algorithms

Overview of Sorting Algorithms Unit 7 Sorting s Simple Sorting algorithms Quicksort Improving Quicksort Overview of Sorting s Given a collection of items we want to arrange them in an increasing or decreasing order. You probably have

More information

10/21/ Linear Search The linearsearch Algorithm Binary Search The binarysearch Algorithm

10/21/ Linear Search The linearsearch Algorithm Binary Search The binarysearch Algorithm 13.1 Linear Search! A linear search simply examines each item in the search pool, one at a time, until either the target is found or until the pool is exhausted! This approach does not assume the items

More information

Using the Debugger. Michael Jantz Dr. Prasad Kulkarni

Using the Debugger. Michael Jantz Dr. Prasad Kulkarni Using the Debugger Michael Jantz Dr. Prasad Kulkarni 1 Debugger What is it a powerful tool that supports examination of your program during execution. Idea behind debugging programs. Creates additional

More information

Programming Studio #9 ECE 190

Programming Studio #9 ECE 190 Programming Studio #9 ECE 190 Programming Studio #9 Concepts: Functions review 2D Arrays GDB Announcements EXAM 3 CONFLICT REQUESTS, ON COMPASS, DUE THIS MONDAY 5PM. NO EXTENSIONS, NO EXCEPTIONS. Functions

More information

CS354 gdb Tutorial Written by Chris Feilbach

CS354 gdb Tutorial Written by Chris Feilbach CS354 gdb Tutorial Written by Chris Feilbach Purpose This tutorial aims to show you the basics of using gdb to debug C programs. gdb is the GNU debugger, and is provided on systems that

More information

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

CSci 4061 Introduction to Operating Systems. Programs in C/Unix CSci 4061 Introduction to Operating Systems Programs in C/Unix Today Basic C programming Follow on to recitation Structure of a C program A C program consists of a collection of C functions, structs, arrays,

More information

Chapter - 17 Debugging and Optimization. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 1

Chapter - 17 Debugging and Optimization. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 1 Chapter - 17 Debugging and Optimization Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 1 Debugging Techniques Divide and conquer Debug only code Debug Command Line Switch Note: Use

More information

CS171 Midterm Exam. October 29, Name:

CS171 Midterm Exam. October 29, Name: CS171 Midterm Exam October 29, 2012 Name: You are to honor the Emory Honor Code. This is a closed-book and closed-notes exam. You have 50 minutes to complete this exam. Read each problem carefully, and

More information

! Search: find a given item in a list, return the. ! Sort: rearrange the items in a list into some. ! list could be: array, linked list, string, etc.

! Search: find a given item in a list, return the. ! Sort: rearrange the items in a list into some. ! list could be: array, linked list, string, etc. Searching & Sorting Week 11 Gaddis: 8, 19.6,19.8 CS 5301 Spring 2015 Jill Seaman 1 Definitions of Search and Sort! Search: find a given item in a list, return the position of the item, or -1 if not found.!

More information

C/C++ Programming Lecture 18 Name:

C/C++ Programming Lecture 18 Name: . The following is the textbook's code for a linear search on an unsorted array. //***************************************************************** // The searchlist function performs a linear search

More information

for (int outercounter = nums.length - 1; outercounter > 0 && swappedthatturn; outercounter --

for (int outercounter = nums.length - 1; outercounter > 0 && swappedthatturn; outercounter -- /* * A small set of sorting algorithms, written in Java and C++ * Note that they are written by a C++ beginner, may contain mistakes * Or bad habits that have to be avoided * @author Kadir Can Çelik */

More information

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << The sum of the integers 1 to 10 is  << sum << endl; Debugging Some have said that any monkey can write a program the hard part is debugging it. While this is somewhat oversimplifying the difficult process of writing a program, it is sometimes more time

More information

! A data type for which: ! An ADT may be implemented using various. ! Examples:

! A data type for which: ! An ADT may be implemented using various. ! Examples: Stacks and Queues Unit 6 Chapter 19.1-2,4-5 CS 2308 Fall 2018 Jill Seaman 1 Abstract Data Type A data type for which: - only the properties of the data and the operations to be performed on the data are

More information

CS Sorting Terms & Definitions. Comparing Sorting Algorithms. Bubble Sort. Bubble Sort: Graphical Trace

CS Sorting Terms & Definitions. Comparing Sorting Algorithms. Bubble Sort. Bubble Sort: Graphical Trace CS 704 Introduction to Data Structures and Software Engineering Sorting Terms & Definitions Internal sorts holds all data in RAM External sorts use Files Ascending : Low to High Descending : High to Low

More information

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger.

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger. UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division CS164 Spring 2008 P. N. Hilfinger The GJDB Debugger A debugger is a program that runs other

More information

CSE 2123 Sorting. Jeremy Morris

CSE 2123 Sorting. Jeremy Morris CSE 2123 Sorting Jeremy Morris 1 Problem Specification: Sorting Given a list of values, put them in some kind of sorted order Need to know: Which order? Increasing? Decreasing? What does sorted order mean?

More information

1 Basic functions of a debugger

1 Basic functions of a debugger UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division CS61B Fall 2014 P. N. Hilfinger The GJDB Debugger A debugger is a program that runs other programs,

More information

Sorting. Quicksort analysis Bubble sort. November 20, 2017 Hassan Khosravi / Geoffrey Tien 1

Sorting. Quicksort analysis Bubble sort. November 20, 2017 Hassan Khosravi / Geoffrey Tien 1 Sorting Quicksort analysis Bubble sort November 20, 2017 Hassan Khosravi / Geoffrey Tien 1 Quicksort analysis How long does Quicksort take to run? Let's consider the best and the worst case These differ

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 7 September 21, 2016 CPSC 427, Lecture 7 1/21 Brackets Example (continued) Storage Management CPSC 427, Lecture 7 2/21 Brackets Example

More information

Lab: Supplying Inputs to Programs

Lab: Supplying Inputs to Programs Steven Zeil May 25, 2013 Contents 1 Running the Program 2 2 Supplying Standard Input 4 3 Command Line Parameters 4 1 In this lab, we will look at some of the different ways that basic I/O information can

More information

Introduction. Sorting. Definitions and Terminology: Program efficiency. Sorting Algorithm Analysis. 13. Sorting. 13. Sorting.

Introduction. Sorting. Definitions and Terminology: Program efficiency. Sorting Algorithm Analysis. 13. Sorting. 13. Sorting. Sorting Introduction Slides. Table of Contents. Introduction 3. Bubblesort 4. Bubblesort Complexity 5. Bubblesort Complexity (cont) 6. Selection Sort 7. Selection Sort Complexity 8. Duplex Selection Sort

More information

CSE 351. GDB Introduction

CSE 351. GDB Introduction CSE 351 GDB Introduction Lab 2 Out either tonight or tomorrow Due April 27 th (you have ~12 days) Reading and understanding x86_64 assembly Debugging and disassembling programs Today: General debugging

More information

! Search: find a given item in a list, return the. ! Sort: rearrange the items in a list into some. ! list could be: array, linked list, string, etc.

! Search: find a given item in a list, return the. ! Sort: rearrange the items in a list into some. ! list could be: array, linked list, string, etc. Searching & Sorting Week 11 Gaddis: 8, 19.6,19.8 (8th ed) Gaddis: 8, 20.6,20.8 (9th ed) CS 5301 Fall 2018 Jill Seaman!1 Definitions of Search and Sort! Search: find a given item in a list, return the position

More information

Part I: Short Answer (12 questions, 65 points total)

Part I: Short Answer (12 questions, 65 points total) CSE 143 Sp01 Final Exam Sample Solution page 1 of 14 Part I: Short Answer (12 questions, 65 points total) Answer all of the following questions. READ EACH QUESTION CAREFULLY. Answer each question in the

More information

Using gdb to find the point of failure

Using gdb to find the point of failure gdb gdb is the GNU debugger on our CS machines. gdb is most effective when it is debugging a program that has debugging symbols linked in to it. With gcc and g++, this is accomplished using the -g option,

More information

Sorting. Sorting in Arrays. SelectionSort. SelectionSort. Binary search works great, but how do we create a sorted array in the first place?

Sorting. Sorting in Arrays. SelectionSort. SelectionSort. Binary search works great, but how do we create a sorted array in the first place? Sorting Binary search works great, but how do we create a sorted array in the first place? Sorting in Arrays Sorting algorithms: Selection sort: O(n 2 ) time Merge sort: O(nlog 2 (n)) time Quicksort: O(n

More information

DATA STRUCTURES AND ALGORITHMS

DATA STRUCTURES AND ALGORITHMS DATA STRUCTURES AND ALGORITHMS Fast sorting algorithms Shellsort, Mergesort, Quicksort Summary of the previous lecture Why sorting is needed? Examples from everyday life What are the basic operations in

More information

Sorting. Sorting. Stable Sorting. In-place Sort. Bubble Sort. Bubble Sort. Selection (Tournament) Heapsort (Smoothsort) Mergesort Quicksort Bogosort

Sorting. Sorting. Stable Sorting. In-place Sort. Bubble Sort. Bubble Sort. Selection (Tournament) Heapsort (Smoothsort) Mergesort Quicksort Bogosort Principles of Imperative Computation V. Adamchik CS 15-1 Lecture Carnegie Mellon University Sorting Sorting Sorting is ordering a list of objects. comparison non-comparison Hoare Knuth Bubble (Shell, Gnome)

More information

CS 11 C track: lecture 6

CS 11 C track: lecture 6 CS 11 C track: lecture 6 Last week: pointer arithmetic This week: The gdb program struct typedef linked lists gdb for debugging (1) gdb: the Gnu DeBugger http://courses.cms.caltech.edu/cs11/material /c/mike/misc/gdb.html

More information

Visual Profiler. User Guide

Visual Profiler. User Guide Visual Profiler User Guide Version 3.0 Document No. 06-RM-1136 Revision: 4.B February 2008 Visual Profiler User Guide Table of contents Table of contents 1 Introduction................................................

More information

Data Structures and Algorithms for Engineers

Data Structures and Algorithms for Engineers 0-630 Data Structures and Algorithms for Engineers David Vernon Carnegie Mellon University Africa vernon@cmu.edu www.vernon.eu Data Structures and Algorithms for Engineers 1 Carnegie Mellon University

More information

CS102 Software Engineering Principles

CS102 Software Engineering Principles CS102 Software Engineering Principles Bill Cheng http://merlot.usc.edu/cs102-s12 1 Software Engineering Principles You need to develop a plan before you start writing your code Choose the proper data structures

More information

Chapter 7 Sorting. Terminology. Selection Sort

Chapter 7 Sorting. Terminology. Selection Sort Chapter 7 Sorting Terminology Internal done totally in main memory. External uses auxiliary storage (disk). Stable retains original order if keys are the same. Oblivious performs the same amount of work

More information

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC CMSC 341 Lecture 6 Templates, Stacks & Queues Based on slides by Shawn Lupoli & Katherine Gibson at UMBC Today s Topics Data types in C++ Overloading functions Templates How to implement them Possible

More information

Exercise Session 6 Computer Architecture and Systems Programming

Exercise Session 6 Computer Architecture and Systems Programming Systems Group Department of Computer Science ETH Zürich Exercise Session 6 Computer Architecture and Systems Programming Herbstsemester 2016 Agenda GDB Outlook on assignment 6 GDB The GNU Debugger 3 Debugging..

More information

Sorting. Bringing Order to the World

Sorting. Bringing Order to the World Lecture 10 Sorting Bringing Order to the World Lecture Outline Iterative sorting algorithms (comparison based) Selection Sort Bubble Sort Insertion Sort Recursive sorting algorithms (comparison based)

More information

COMP1511 focuses on writing programs. Effciency is also important. Often need to consider:

COMP1511 focuses on writing programs. Effciency is also important. Often need to consider: Efficiency COMP1511 focuses on writing programs. Effciency is also important. Often need to consider: execution time memory use. A correct but slow program can be useless. Efficiency often depends on the

More information

University of Toronto

University of Toronto University of Toronto Faculty of Applied Science and Engineering Midterm Solutions October, 2008 ECE244 --- Programming Fundamentals Examiners: Courtney Gibson, Ashvin Goel, and Michael Stumm Instructions:

More information

Week 3: Pointers (Part 2)

Week 3: Pointers (Part 2) Advanced Programming (BETC 1353) Week 3: Pointers (Part 2) Dr. Abdul Kadir abdulkadir@utem.edu.my Learning Outcomes: Able to describe the concept of pointer expression and pointer arithmetic Able to explain

More information

LECTURE 17. Array Searching and Sorting

LECTURE 17. Array Searching and Sorting LECTURE 17 Array Searching and Sorting ARRAY SEARCHING AND SORTING Today we ll be covering some of the more common ways for searching through an array to find an item, as well as some common ways to sort

More information

Sorting. Order in the court! sorting 1

Sorting. Order in the court! sorting 1 Sorting Order in the court! sorting 1 Importance of sorting Sorting a list of values is a fundamental task of computers - this task is one of the primary reasons why people use computers in the first place

More information

SYSC 2006 Winter 2012 Linear Collections: Queues

SYSC 2006 Winter 2012 Linear Collections: Queues SYSC 2006 Winter 2012 Linear Collections: Queues Copyright 2000-2012 D.L. Bailey, Systems and Computer Engineering, Carleton University revised March 20, 2011, November 28, 2011, March 30, 2012 Definition

More information

// walk through array stepping by step amount, moving elements down for (i = unsorted; i >= step && item < a[i-step]; i-=step) { a[i] = a[i-step];

// walk through array stepping by step amount, moving elements down for (i = unsorted; i >= step && item < a[i-step]; i-=step) { a[i] = a[i-step]; Sorting (Rosen, 6 th edition) Carol Zander So far, we have examined only O(n 2 ) algorithms (bubble, insertion, selection). We will now look at more efficient algorithms. Most are recursive, but the first

More information

ECE/ME/EMA/CS 759 High Performance Computing for Engineering Applications

ECE/ME/EMA/CS 759 High Performance Computing for Engineering Applications ECE/ME/EMA/CS 759 High Performance Computing for Engineering Applications Elements of Program Debugging Dan Negrut, 2017 ECE/ME/EMA/CS 759 UW-Madison Debugging on Euler [with gdb] Slides on gdb include

More information

Quicksort. Repeat the process recursively for the left- and rightsub-blocks.

Quicksort. Repeat the process recursively for the left- and rightsub-blocks. Quicksort As the name implies, this is the fastest known sorting algorithm in practice. It is excellent for average input but bad for the worst-case input. (you will see later). Basic idea: (another divide-and-conquer

More information

CS2141 Software Development using C/C++ C++ Basics

CS2141 Software Development using C/C++ C++ Basics CS2141 Software Development using C/C++ C++ Basics Integers Basic Types Can be short, long, or just plain int C++ does not define the size of them other than short

More information

Sorting. Order in the court! sorting 1

Sorting. Order in the court! sorting 1 Sorting Order in the court! sorting 1 Importance of sorting Sorting a list of values is a fundamental task of computers - this task is one of the primary reasons why people use computers in the first place

More information

Sorting. CSC 143 Java. Insert for a Sorted List. Insertion Sort. Insertion Sort As A Card Game Operation CSC Picture

Sorting. CSC 143 Java. Insert for a Sorted List. Insertion Sort. Insertion Sort As A Card Game Operation CSC Picture CSC 43 Java Sorting Reading: Sec. 9.3 Sorting Binary search is a huge speedup over sequential search But requires the list be sorted Slight Problem: How do we get a sorted list? Maintain the list in sorted

More information

Interview Questions of C++

Interview Questions of C++ Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.

More information

ECE264 Fall 2013 Exam 1, September 24, 2013

ECE264 Fall 2013 Exam 1, September 24, 2013 ECE264 Fall 2013 Exam 1, September 24, 2013 In signing this statement, I hereby certify that the work on this exam is my own and that I have not copied the work of any other student while completing it.

More information

MPATE-GE 2618: C Programming for Music Technology. Unit 4.2

MPATE-GE 2618: C Programming for Music Technology. Unit 4.2 MPATE-GE 2618: C Programming for Music Technology Unit 4.2 Quiz 1 results (out of 25) Mean: 19.9, (standard deviation = 3.9) Equivalent to 79.1% (SD = 15.6) Median: 21.5 High score: 24 Low score: 13 Pointer

More information

Jordan University of Science & Technology Department of Computer Science CS 211 Exam #1 (23/10/2010) -- Form A

Jordan University of Science & Technology Department of Computer Science CS 211 Exam #1 (23/10/2010) -- Form A Jordan University of Science & Technology Department of Computer Science CS 211 Exam #1 (23/10/2010) -- Form A Name: ID#: Section #: Day & Time: Instructor: Answer all questions as indicated. Closed book/closed

More information

III. Classes (Chap. 3)

III. Classes (Chap. 3) III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,

More information

Common Misunderstandings from Exam 1 Material

Common Misunderstandings from Exam 1 Material Common Misunderstandings from Exam 1 Material Kyle Dewey Stack and Heap Allocation with Pointers char c = c ; char* p1 = malloc(sizeof(char)); char** p2 = &p1; Where is c allocated? Where is p1 itself

More information

Chapter 13. If the list is in increasing order; no interchanges are required.

Chapter 13. If the list is in increasing order; no interchanges are required. Chapter : Sorting Exercises.. After first pass, elements of x are: 0 50 70 0 0 60. After second pass: 0 0 70 50 0 60. 2. (a) 60 70 50 0 20 0 70 60 50 0 20 0 (b) (c), since no interchanges occur on the

More information

Introduction. Sorting. Table of Contents

Introduction. Sorting. Table of Contents Sorting Introduction Table of Contents Introduction Bubblesort Selection Sort Duplex Selection Sort Duplex Selection Sort (cont) Comparison Analysis Comparison Analysis (cont) Time Analysis Time Analysis

More information

CSE 333 Autumn 2013 Midterm

CSE 333 Autumn 2013 Midterm CSE 333 Autumn 2013 Midterm Please do not read beyond this cover page until told to start. A question involving what could be either C or C++ is about C, unless it explicitly states that it is about C++.

More information

Problem Set 1: Unix Commands 1

Problem Set 1: Unix Commands 1 Problem Set 1: Unix Commands 1 WARNING: IF YOU DO NOT FIND THIS PROBLEM SET TRIVIAL, I WOULD NOT RECOMMEND YOU TAKE THIS OFFERING OF 300 AS YOU DO NOT POSSESS THE REQUISITE BACKGROUND TO PASS THE COURSE.

More information

CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion

CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion CSCI-1200 Data Structures Spring 2018 Lecture 7 Order Notation & Basic Recursion Review from Lectures 5 & 6 Arrays and pointers, Pointer arithmetic and dereferencing, Types of memory ( automatic, static,

More information

Chapter 2. Procedural Programming

Chapter 2. Procedural Programming Chapter 2 Procedural Programming 2: Preview Basic concepts that are similar in both Java and C++, including: standard data types control structures I/O functions Dynamic memory management, and some basic

More information

We first learn one useful option of gcc. Copy the following C source file to your

We first learn one useful option of gcc. Copy the following C source file to your Lecture 5 p.1 Faculty of Computer Science, Dalhousie University CSCI 2132 Software Development Lab 5: gcc and gdb tools 10-Oct-2018 Location: Teaching Labs Time: Thursday Instructor: Vlado Keselj Lab 5:

More information

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Data Structures and Algorithms. Final Examination

University of Waterloo Department of Electrical and Computer Engineering ECE 250 Data Structures and Algorithms. Final Examination University of Waterloo Department of Electrical and Computer Engineering ECE 250 Data Structures and Algorithms Instructor: Douglas Wilhelm Harder Time: 2.5 hours Aides: none 14 pages Final Examination

More information

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination University of Illinois at Urbana-Champaign Department of Computer Science First Examination CS 225 Data Structures and Software Principles Spring 2007 7p-9p, Thursday, March 1 Name: NetID: Lab Section

More information

Debugging. Marcelo Ponce SciNet HPC Consortium University of Toronto. July 15, /41 Ontario HPC Summerschool 2016 Central Edition: Toronto

Debugging. Marcelo Ponce SciNet HPC Consortium University of Toronto. July 15, /41 Ontario HPC Summerschool 2016 Central Edition: Toronto Debugging Marcelo Ponce SciNet HPC Consortium University of Toronto July 15, 2016 1/41 Ontario HPC Summerschool 2016 Central Edition: Toronto Outline Debugging Basics Debugging with the command line: GDB

More information

CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory

CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory Announcements CSCI-1200 Data Structures Spring 2016 Lecture 6 Pointers & Dynamic Memory There will be no lecture on Tuesday, Feb. 16. Prof. Thompson s office hours are canceled for Monday, Feb. 15. Prof.

More information

Wawrzynek & Weaver CS 61C. Sp 2018 Great Ideas in Computer Architecture MT 1. Print your name:,

Wawrzynek & Weaver CS 61C. Sp 2018 Great Ideas in Computer Architecture MT 1. Print your name:, Wawrzynek & Weaver CS 61C Sp 2018 Great Ideas in Computer Architecture MT 1 Print your name:, (last) (first) I am aware of the Berkeley Campus Code of Student Conduct and acknowledge that any academic

More information

ENGI 1020 Introduction to Computer Programming J U L Y 5, R E Z A S H A H I D I

ENGI 1020 Introduction to Computer Programming J U L Y 5, R E Z A S H A H I D I ENGI 1020 Introduction to Computer Programming J U L Y 5, 2 0 1 0 R E Z A S H A H I D I Passing by value Recall that it is possible to call functions with variable names different than the parameters in

More information

CSE 374 Programming Concepts & Tools

CSE 374 Programming Concepts & Tools CSE 374 Programming Concepts & Tools Hal Perkins Fall 2017 Lecture 11 gdb and Debugging 1 Administrivia HW4 out now, due next Thursday, Oct. 26, 11 pm: C code and libraries. Some tools: gdb (debugger)

More information