Lab6 - DataStructures
Lab6 - DataStructures
Lab6 - DataStructures
School of EECE
Department of Computer Engineering
6.2 INTRODUCTION
Sorting Algorithms
Selection Sort
Selection sort is one of the O(n2) sorting algorithms, which makes it quite inefficient for sorting
large data volumes. Selection sort is notable for its programming simplicity and it can over perform
other sorts in certain situations.
Algorithm
The idea of algorithm is quite simple. Array is imaginary divided into two parts - sorted
one and unsorted one. At the beginning, sorted part is empty, while unsorted
one contains whole array. At every step, algorithm finds minimal element in the unsorted
part and adds it to the end of the sorted one. When unsorted part becomes empty,
algorithmstops.
When algorithm sorts an array, it swaps first element of unsorted part with minimal element and
then it is included to the sorted part. This implementation of selection sort in not stable. In case
of linked list is sorted, and, instead of swaps, minimal element is linked to the unsorted part,
selection sort is stable.
Insertion Sort
Although it is one of the elementary sorting algorithms with O(n2) worst-case time, insertion sort is
the algorithm of choice either when the data is nearly sorted (because it is adaptive) or when the
problem size is small (because it has low overhead).
For these reasons, and because it is also stable, insertion sort is often used as the recursive base
case (when the problem size is small) for higher overhead divide-and-conquer sorting algorithms,
such as merge sort or quick sort.
Algorithm
Insertion sort algorithm somewhat resembles selection sort. Array is imaginary divided into two
parts - sorted one andunsorted one. At the beginning, sorted part contains first element of the
array and unsorted one contains the rest. At every step, algorithm takes first element in
the unsorted part and inserts it to the right place of the sorted one. Whenunsorted
part becomes empty, algorithm stops.
Quicksort
Quicksort is a fast sorting algorithm, which is used not only for educational purposes, but widely
applied in practice. On the average, it has O(n log n) complexity, making quicksort suitable for
sorting big data volumes. The idea of the algorithm is quite simple and once you realize it, you can
write quicksort as fast as bubble sort.
Algorithm
The divide-and-conquer strategy is used in quicksort. Below the recursion step is described:
1. Choose a pivot value. We take the value of the middle element as pivot value, but it can be
any value, which is in range of sorted values, even if it doesn't present in the array.
2. Partition. Rearrange elements in such a way, that all elements which are lesser than the
pivot go to the left part of the array and all elements greater than the pivot, go to the right
part of the array. Values equal to the pivot can stay in any part of the array. Notice, that
array may be divided in non-equal parts.
3. Sort both parts. Apply quicksort algorithm recursively to the left and the right
parts.
Bubble Sort
Bubble sort is a simple and well-known sorting algorithm. It is used in practice once in a blue moon
and its main application is to make an introduction to the sorting algorithms. Bubble sort belongs to
O(n2) sorting algorithms, which makes it quite inefficient for sorting large data volumes. Bubble sort
is stable and adaptive.
Algorithm
1. Compare each pair of adjacent elements from the beginning of an array and, if they are in
reversed order, swap them.
2. If at least one swap has been done, repeat step 1.
You can imagine that on every step big bubbles float to the surface and stay there. At the step,
when no bubble moves, sorting stops.
Merge Sort
Algorithm
Assume, that both arrays are sorted in ascending order and we want resulting array to maintain
the same order. Algorithm to merge two arrays A[0..m-1] and B[0..n-1] into an array C[0..m+n-
1] is as following:
Sample Programs
A. Selection Sort
Instructions: Create a new project (Lab6) in the same solution (e.g. Mapua.DataStruct) you created
in the previous lab. Name the source file SelectionSort-ArrayBasedList.cpp. See example full path
below:
Z:\Mapua.DataStruct\Lab6\SelectionSort-ArrayBasedList.cpp
72. A
73. A}
74. A
75. A
76. Atemplate<class elemType>
77. Avoid ArrayListType<elemType>::PrintList(){
78. A for(int i=0; i<length; ++i)
79. A {
80. A cout<<list[i]<<" ";
81. A }
82. A cout<<"\n";
83. A //list = NULL; //to avoid HEAP corruption
84. A
85. A}
86. A
87. Atemplate<class elemType>
88. Aint ArrayListType<elemType>::SeqSearch(const elemType &item) const{
89. A int loc;
90. A bool found = false;
91. A for(loc = 0; loc <length; loc++)
92. A if (list[loc] == item)
93. A {
94. A found =true;
95. A break;
96. A }
97. A if(found) return loc;
98. A else return -1;
99. A}
100. A
101. Atemplate<class elemType>
102. Avoid ArrayListType<elemType>::Insert(const elemType& item)
103. A{
104. A int loc;
105. A if(length ==0) //list is empty
106. A list[length++] = item;
107. A else if(length==maxSize)
108. A cerr<<"Cannot insert in a full list."<<endl;
109. A else
110. A {
111. A loc = SeqSearch(item);
112. A if (loc == -1)
113. A list[length++] = item;
114. A else
115. A cerr<<"the item to be inserted is already in"
116. A <<"the list. No duplication is allowed."<<endl;
117. A }
118. A}
119. A
120. A// MinLocation - function that returns the index
121. A// of the smallest element
172. A
173. A alphabet.SelectionSort();
174. A cout<<"The list before using selection sort: "<<endl;
175. a alphabet.PrintList();
176. a
177. a
178. a system("pause");
179. a return 0;
180. A}
Instructions: Build the project. Run the program and use the inputs shown in Figure 6.1
B. Insertion Sort
Instructions: Add the source file shown in Program Listings 6.2.A, 6.2.B, 6.2.C, 6.2.D,
and 6.2.E. Remember to exclude the previous file. Name the files as QueueClass.h. ,
QueueClass.cpp, and Lab4-Sample04(ArrayImplementation).cpp respectively. Build the
file and trace the program execution.
8. #define LinkedListType_h
9.
10. //Node definition
11.
12. template<class Type>
13. struct nodeType
14. {
15. Type info;
16. nodeType<Type> * link;
17. A};
18. A
19. Atemplate<class Type>
20. Aclass LinkedListIterator
21. A{
22. Apublic:
23. A LinkedListIterator(); //default constructor
24. A
25. A LinkedListIterator(nodeType<Type> *ptr); //constructor with 1
26. Aparameter
27. A
28. A Type operator*(); //overload the dereference operator
29. A LinkedListIterator<Type> operator++(); //overload the preincrement
30. Aoperator
31. A
32. A bool operator==(const LinkedListIterator<Type>& right) const;
33. A//overload the equality operator
34.
35. private:
36. A nodeType<Type> * current; //pointer to point to the current node in
37. Athe linked list
38. A};
39. A
40. Atemplate<class Type>
41. Aclass LinkedListType
42. A{
43. Apublic:
44. A //Overload the assignment operator
45. A const LinkedListType<Type>& operator = (const
46. ALinkedListType<Type>&);
47. A void InitializeList();
48. A bool IsEmptyList() const;
49. A void Print() const;
50. A int Length() const;
51. A void DestroyList();
52. A
53. A Type front() const;
54. A Type back() const;
55. A
56. A virtual bool Search(const Type& searchItem) const = 0;
57. A virtual void InsertFirst(const Type& newItem) = 0;
76. A}
77. A
78. Atemplate <class Type>
79. ALinkedListIterator<Type>::LinkedListIterator(nodeType<Type> *ptr)
80. A{
81. A current = ptr;
82. A}
83. A
84. Atemplate <class Type>
85. AType LinkedListIterator<Type>::operator*()
86. A{
87. A return current->info;
88. A}
89. A
90. Atemplate <class Type>
91. ALinkedListIterator<Type> LinkedListIterator<Type>::operator++()
92. A{
93. A current = current->link;
94. A return *this;
95. A}
96. A
97. A template <class Type>
98. Abool LinkedListIterator<Type>::operator==(const LinkedListIterator<Type>&
99. Aright) const
100.{ A
101. Areturn (current != right.current);
102.} A
103. A
104.#endifA
86. A
87. Atemplate<class Type>
88. Avoid UnorderedLinkedList<Type>::InsertLast(const Type& newItem)
89. A{
90. A nodeType<Type> *newNode;//pointer to create the new node;
91. A newNode = new nodeType<Type>;
92. A newNode->info = newItem;
93. A newNode->link = NULL;
94. A
95. A if(first==NULL)
96. A {
97. A first = newNode;
98. A last = newNode;
99. a count++;
100. a}
101. aelse
102. a{
103. a last->link = newNode;
104. a last = newNode;
105. a count++;
106. a}
107.} a
108. a
109.template<class
a Type>
110.void UnorderedLinkedList<Type>::DeleteNode(const
a Type& deleteItem)
111.{ a
112. anodeType<Type> *current ;
113. anodeType<Type> *trailCurrent;
114. abool found;
115. a
116. aif(first==NULL)
117. a cout<<"Cannot delete from an empty list"<<endl;
118. aelse
119. a{
120. a if(first->info == deleteItem)
121. a {
122. a current = first;
123. a first = first->link;
124. a count--;
125. a
126. a if(first ==NULL)
127. a last = NULL;
128. a delete current;
129. a }
130. a else
131. a {
132. a found = false;
133. a trailCurrent = first;
134. a current=first->link;
135. a
6.4 QUESTIONS
2. Both mergesort and quicksort sort a list by partitioning the list. Explain how mergesort
differs from quicksort in partitioning the list.
Filenames:
Class Definition: Lab6-ProgExer02.h
Class Implementation: Lab6-ProgExer03.cpp
Entry Point: Lab6-ProgExer02-Entry.cpp
3. Write a C++ program that implements quicksort algorithm. Assume the following list of
keys: 16, 38, 54, 80, 22, 65, 55, 48, 64, 95, 5, 100, 58, 25, 36. Use pivot as the middle
element of the list. Display the resulting list after one call to the partition procedure and the
resulting list after two calls to the partition procedure.
Filenames:
Class Definition: Lab6-ProgExer03.h
Class Implementation: Lab6-ProgExer03.cpp
Entry Point: Lab6-ProgExer03-Entry.cpp