notes73

notes73 - Correctionfor(int i = 0 i< n 1 i{for(int j = 0...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon

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

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 1-24-2005Correctionfor(int i = 0; i < n - 1; i++){for(int j = 0; j < n - i; j++) // Originally: for(int j = i; j < n - 1; j++);{if(A[j] > A[j + 1]){int tmp = A[j];A[j] = A[j + 1];A[j + 1] = tmp;}}}•The highest number always goes to the end of the array.•The asymptotic analysis proves that the bubble sort will take O(n^2). Public:QueueArray(int max){_max = max;_head = 0;_tail = 0;_n = 0;_array = new int[max];}void add(int element){assert(_n < _max);_array[_tail] = element;_tail = (_tail + 1) % _max; // wrap if necessary_n++;}int remove(){assert(_n > 0);int tmp = _array[_head];_head = (_head + 1) % _max; // wrap if necessary_n--;return tmp;}}You can also implement a queue using a single-linked list:You need two pointers: _head (points to the beginning of the list) and _tail (points to the end of the list).Removing an arbitrary node from a single-linked list takes time O(n) because we need to traverse the list to find the previous node.Initially_head -> NULL_tail -> NULLadd(1)_head -> 1 -> NULL_tail -> 1add(3)_head -> 1 -> 3 -> NULL_tail -> 3remove()_head -> 3 -> NULL_tail -> 3return 1 To remove the node pointed by "p", we need to find the node previous to "p" (called "q") and then make q -> next = p -> next....
View Full Document

This note was uploaded on 02/02/2012 for the course CS 251 taught by Professor Staff during the Fall '08 term at Purdue.

Page1 / 6

notes73 - Correctionfor(int i = 0 i< n 1 i{for(int j = 0...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online