Implementation of Sorting Algorithms
Implementation of Sorting Algorithms
SORTING ALGORITHMS
BY
MARCH, 2012
i
CERTIFICATION
This is to certify that this work was carried out by ERINFOLAMI, Daniel
University, Ado-Ekiti,
____________________ _____________________
Mr. A.A. Obayomi DATE
PROJECT SUPERVISOR
____________________ _____________________
Dr. R.A. Adeleke DATE
HEAD OF DEPARTMENT
____________________ _____________________
External Examiner DATE
ii
DEDICATION
This project is dedicated to Almighty God for his guidance, protection and
to my family and friends for the encouragement, moral and financial support
given to me.
iii
ACKNOWLEDGEMENTS
A Big thanks to Almighty God the maker of Heaven and Earth who
for me like a father to his son, who took time in going through this project
corrections for the success of this project, I say a big thank you.
To my parents, Pastor & Mrs. Erinfolami who has always being there
for me, spiritually, financially and morally, you gave me the best gift of life
There are many to whom I owe a debt of gratitude for their valuable
suggestions, love and wonderful support all the way, More importantly Mr.
siblings, I say thank you for your love and support, May God reward you
bountifully. I love you so much, thanks for being there. I cannot forget my
iv
friends; Akinwale Emmanuel Michael Falade, Samuel, Cecilia, and the
members of CAC Victory Assembly, EKSU, who all have been so loving and
have been such good people to me, it’s been a privilege meeting you all.
v
TABLE OF CONTENTS
CONTENTS PAGES
TITLE PAGE i
CERTIFICATION ii
DEDICATION iii
ACKNOWLEDGEMENTS iv
TABLE OF CONTENTS vi
ABSTRACT xi
1.1 Introduction 1
1.3 Methodology 6
vi
CHAPTER TWO: LITERATURE REVIEW
2.2 Terminologies 10
2.3 Concepts 13
2.4 Classification 18
2.5 Stability 19
2.6.7 JSort 27
vii
2.6.12 Selection Sort 34
2.7 Comparison 39
3.1 Introduction 47
viii
CHAPTER FOUR: SYSTEM IMPLEMENTATION
5.1 Conclusion 60
5.2 Recommendation 60
REFERENCES 61
APPENDICES 63
ix
Appendix C: Sorting Algorithms in Visual Basic 69
x
ABSTRACT
Descriptions are brief with just enough theory. The first section introduces
section presents several sorting algorithms. Source code for the most
the items being sorted are more complex, typically objects or structs, so that
xi
xii
CHAPTER ONE
1.1 INTRODUCTION
According to Wikipedia,
different sets, and accordingly, it has two common, yet distinct meanings:
1. Ordering: arranging items of the same kind, class, nature, etc. in some
ordered sequence,
sorted are more complex, typically objects or structs, so that each item is
itself made up of a number of elements. We will refer to the items that are
being sorted as records and to the elements that make up the items as fields
1
components. For example, if each record is a name and address, then the
fields might be first name, last name, street address, city, state, and zip code.
on only one of the fields of the record. This field is said to be the key field for
the sort (or sort key), and the values of this field are called keys. In other
the records so that their keys are in ascending (or descending) order.
A new sort key can be created from two or more sort keys by
lexicographical order. The first is then called the primary sort key, the
For example, addresses could be sorted using the city as primary sort key,
If the sort key values are totally ordered, the sort key defines a weak order of
the items: items with the same sort key are equivalent with respect to
sorting. See also stable sorting. If different items have different sort key
2
A standard order is often called ascending (corresponding to the fact that
earlier values precede later ones e.g. 1/1/2000 will sort ahead of 1/1/2001.
certain order. The most used orders are numerical and lexicographical order.
(such as search and merge algorithms) that require sorted lists to work
correctly; it is often useful for canonicalizing data and for producing human-
readable output.
3
SORTING EXAMPLES:
Highest to Lowest.
alphabetical order.
WHY DO WE SORT?
or database application).
4
1.2 AIMS AND OBJECTIVES OF THE PROJECT
Show that the worse-case asymptotic behavior is not always the best
Show that the initial condition (input order and key distribution)
5
Randomize an array, and
1.3 METHODOLOGY
This project work has benefitted majorly from information gathered from
of sorting.
6
External sorting, radix sorting, string sorting, and linked list sorting – all
iii. Chapter Three (System Design and Analysis): discusses how the
7
hardware and software requirement for installation and the process of
installation itself.
will be suggested.
8
CHAPTER TWO
LITERATURE REVIEW
updating was done by sorting transactions and merging them with a master
file. It's still important for presentation of data extracted from databases:
most people prefer to get reports sorted into some relevant order before
category e.g. a shopping catalogue where items are compiled together under
headings such as 'home', 'sport & leisure', 'women's clothes' etc. (nominal
9
scale) and by the intensity of some property, such as price, e.g. from the
2.2 Terminologies
a) Algorithm:
ending state.
b) Lists:
collection of values, where the same value may occur more than once. An
10
item, entry, or element of the list; if the same value occurs multiple times,
c) Array:
array index or key. An array is stored so that the position of each element
Arrays are among the oldest and most important data structures, and are
used by almost every program. They are also used to implement many other
When data objects are stored in an array, individual objects are selected by
an index that is usually a non-negative scalar integer. Indices are also called
There are three ways in which the elements of an array can be indexed:
subscript of 0.
11
1 (one-based indexing): The first element of the array is indexed by
subscript of 1.
d) Search Algorithm:
e) N-Tuple:
implicitly, is another word for a list, i.e., an ordered set of n elements. It can
12
2.3 Concepts
a) Big O Notation:
b) Timing Estimates
execution time increases with the square of the dataset size. For example, if
Assume that execution time is some function t(n), where n is the dataset
t(n) = O(g(n))
13
t(n) <= c·g(n)
for all n greater than or equal to n0. This is illustrated graphically in the
following figure.
Big-oh notation does not describe the exact time that an algorithm takes,
constant factor. If an algorithm takes O(n2) time, then execution time grows
14
7/6 2
n lg n n n lg n n
1 0 1 0 1
16 4 25 64 256
256 8 645 2,048 65,536
4,096 12 16,384 49,152 16,777,216
65,536 16 416,128 1,048,565 4,294,967,296
1,048,576 20 10,568,983 20,971,520 1,099,511,627,776
16,777,216 24 268,435,456 402,653,183 281,474,976,710,656
Table 1-1 illustrates growth rates for various functions. A growth rate of
O(lg n) occurs for algorithms similar to the binary search. The lg (logarithm,
search twice as many items with one more comparison in the binary search.
chapters a timing estimate for each algorithm, using big-O notation, will be
included. For a more formal derivation of these formulas you may wish to
15
c) Divide and Conquer Algorithms:
the same (or related) type, until these problems become simple enough to be
This technique is the basis of efficient algorithms for all kinds of problems
d) Data Structures:
16
e) Best, Worst and Average Case:
Best, Worst and Average Cases of a given algorithm express what the
might be needed in the worst case to guarantee that the algorithm will
This is a situation where the memory use can be reduced at the cost of
reduced at the cost of increased memory use). As the relative costs of CPU
cycles, RAM space, and hard drive space change – hard drive space has for
some time been getting cheaper at a much faster rate than other components
17
2.4 CLASSIFICATION
element comparisons in terms of the size of the list (n). For typical
O(n2). Ideal behavior for a sort is O(n), but this is not possible in the
18
elements of the list via an abstract key comparison operation, need at
sorts include bubble sort and quicksort. Selection sorts include shaker
running time. Algorithms that take this into account are known to be
adaptive.
2.5 STABILITY
A sorting algorithm is said to be stable if items that have the same key
remain in the same relative order after the sorting algorithm is applied as
ordering of items with the same key. In Selection Sort, on the other hand, an
19
item can jump from one part of the array to another, moving past other
items with the same key. Selection Sort is not stable. Similarly, Heap Sort is
some cases. Suppose, for example, we are sorting records that contain first
name and last name fields. Suppose that we sort the array using the first
name as the key, and then we sort using the last name as key. If we use a
stable sorting algorithm, then records with the same last name will still be
people with the same last name can end up in an arbitrary order. [3]
through the list to be sorted, comparing two items at a time and swapping
them if they are in the wrong order. The pass through the list is repeated
20
Figure 2-2: A Visual Representation of How Bubble Sort Works
The algorithm gets its name from the way smaller elements "bubble" to the
top (i.e. the beginning) of the list via the swaps. One way to optimize
bubble sort (implemented here) is to note that, after each pass, the largest
element will always move down to the bottom. Thus it suffices to sort the
except in education.
21
2.6.2. Cocktail Sort
Cocktail sort is a variation of bubble sort that sorts in both directions each
whether there has been a swap after the first pass each iteration. If there
hasn't been a swap the list is sorted and the algorithm can stop.
Comb sort was invented by Stephen Lacey and Richard Box, who first
in speed more complex algorithms like quick sort. The idea is to eliminate
turtles, or small values near the end of the list, since in a bubble sort these
slow the sorting down tremendously. (Rabbits, large values around the
In bubble sort, when any two elements are compared, they always have a
gap (distance from each other) of one. The basic idea of comb sort is that the
22
The gap starts out as the length of the list being sorted divided by the shrink
factor, and the list is sorted with that value (rounded down to an integer if
needed) for the gap. Then the gap is divided by the shrink factor again, the
list is sorted with this new gap, and the process repeats until the gap is one.
At this point, comb sort reverts to a true bubble sort, using a gap of one
until the list is fully sorted. In this final stage of the sort most turtles have
The shrink factor has a great effect on the efficiency of comb sort. In the
original article, the authors suggested 1.3 after trying some random lists and
finding it to be generally the most effective. A value too small slows the
loops. In practice the algorithm has been reported to generally run as fast as
23
Insertion sort, although this depends on the details of the architecture and
the implementation
property: if B is a child node of A, then key(A) >= key(B). This implies that
the element with the greatest key is always in the root node. All elements to
be sorted are inserted into a heap, and the heap organizes the elements
added to it in such a way that the largest value can be quickly extracted.
Once the data list has been made into a heap, the root node is guaranteed to
be the largest element. It is removed and placed at the end of the list, then
the heap is rearranged so the largest element remaining moves to the root.
Using the heap, finding the next largest element takes much less time than
scanning every remaining element, which gives heap sort much better
24
performance than selection sort. Similar to selection sort, the initial
sort is a simple comparison sort in which the sorted array (or list) is built
one entry at a time. It is much less efficient on large lists than more
advanced algorithms such as quicksort, heap sort, or merge sort, but it's very
efficient on small (5-50 key) lists, as well as lists that are mostly sorted to
begin with.
25
Figure 2-3: Insertion Sort
from the input data, inserting it at the correct position in the already sorted
list, until no elements are left in the input. The choice of which element to
remove from the input is arbitrary and can be made using almost any choice
algorithm.
26
2.6.7. JSort
Morrison. It works by running two heap passes to roughly order the array,
The first heap pass converts the array to a heap, moving the smallest item to
the top. The second heap pass works in reverse, moving the largest element
to the bottom. These two passes combine to roughly order the array, though
For small lists, JSort is extremely efficient, but due to its design it does not
scale well.
Similar to shell sort and comb sort, jump sort employs a gap value that
moved very far initially. The underlying framework is based on bubble sort
instead of the more efficient insertion sort, but due to the initial ordering in
the early passes it ends up being very efficient in practice, though still
halves. Each half is then sorted independently, and the two sorted halves are
Instead, the implementation here uses the purest form of merge sort, where
the list is recursively divided into halves until it reaches a list size of two, at
copy of the initial array. There are various optimizations that can be made to
28
Invented in 1945 by John von Neumann, merge sort is far and away the
operation.
compared against every other element. All smaller elements are moved
before the pivot, and all larger elements are moved after. The lesser and
greater sublists are then recursively processed until the entire list is sorted.
However, in the (very rare) worst case quick sort is as slow as bubble sort.
There are good sorting algorithms with a better worst case, e.g. heap sort
and merge sort, but on the average they are slower than quick sort by a
consistent margin.
29
int function Partition (Array A, int Lb, int Ub);
begin
select a pivot from A[Lb]...A[Ub];
reorder A[Lb]...A[Ub] such that:
all values to the left of the pivot are <= pivot
all values to the right of the pivot are >= pivot
return pivot position;
end;
The implementation here uses Niklaus Wirth's variant for selecting the
pivot value, which is simply using the middle value. This works particularly
In Figure 2-5(a), the pivot selected is 3. Indices are run starting at both ends
of the array. One index starts on the left and selects an element that is larger
than the pivot, while another index starts on the right and selects an
element that is smaller than the pivot. In this case, numbers 4 and 1 are
This process repeats until all elements to the left of the pivot <= the pivot,
30
and all elements to the right of the pivot are >= the pivot. Quick Sort
recursively sorts the two sub arrays, resulting in the array shown in Figure
2-5(c).
Its speed and modest space usage makes quick sort one of the most popular
The shaded element is the pivot. It is always chosen as the last element of
the partition. However, always choosing the last element in the partition as
31
Figure 2-5: Quicksort Example 2
elements crop up a lot towards the end of a sorting procedure on a large set,
versions of the quicksort algorithm which choose the pivot as the middle
element run much more quickly than the algorithm described in this
32
2.6.11. Quick Sort 3
The critical operation in the standard quick sort is choosing a pivot: the
element around which the list is partitioned. The simplest pivot selection
algorithm is to take the first or the last element of the list as the pivot,
causing poor behavior for the case of sorted or nearly-sorted input. Niklaus
The median-of-3 pivot selection algorithm takes the median of the first,
middle, and last elements of the list; however, even though this performs
killer list that will cause dramatic slowdown of a quicksort based on this
aggressor, for example by sending such a list to an Internet server for sorting
instead of using the first, last and middle elements, three elements are
33
attacks, though there is still a possibility (however remote) of realizing the
Selection sort is a simple sorting algorithm that mimics the way humans
instinctively sort. It works by first scanning the entire list to find the
smallest element, swapping it into the first position. It then finds the next
smallest element, swapping that into the second position, and so on until
Selection sort is unique compared to almost any other algorithm in that its
running time is not affected by the prior ordering of the list; it always
Selection sort also requires only n swaps, which can be very attractive if
selection sort that is both very fast and also scales well.
34
2.6.13. Shaker Sort
Shaker sort is a gap-based bubble sort with a twist. Most gap sorts -- shell
sort, comb sort, et al. -- begin with a large gap and gradually shrink it down
to one. By the time the gap reaches one, the list should be mostly ordered so
Like other gap sorts, shaker sort begins with a large gap which gradually
shrinks. However, once the gap reaches one, the gap gets expanded again
before shrinking back toward one. The expanding and contracting gap sizes
expansion is done. At this point the list is almost certain to be nearly sorted,
Shell sort is a variation of insertion sort that was invented by (and takes its
gap of several positions. This lets an element take "bigger steps" toward its
35
expected position. Multiple passes over the data are taken using insertion
sort with smaller and smaller gap sizes. The last step of Shell sort is with a
the final list is sorted. By then, the list will be almost sorted already, so the
increment sequence will work, so long as the last element is 1. Donald Shell
originally suggested a gap sequence starting at half the size of the list,
formula x=3x+1, where x starts at 0 and grows until the gap is larger than the
list size. Each insertion sort loop begins by dividing the gap by three, thus
36
Figure 2-7: Shell Sort
A key feature of shell sort is that the elements remain k-sorted even as the
gap diminishes. For instance, if a list was 5-sorted and then 3-sorted, the list
is now not only 3-sorted, but both 5- and 3-sorted. If this were not true, the
algorithm would undo work that it had done in previous iterations, and
Although shell sort is inefficient for large data sets, it is one of the fastest
algorithms for sorting small numbers of elements (sets with less than 1000
37
enjoyed a brief period when it was the fastest sorting algorithm known, only
Smooth sort has a similar average case to heap sort but a much better best
case, with a smooth transition between the two. This is where the name
comes from. The advantage of smooth sort is that it's faster if the input is
faster than any other algorithm, including quick sort, and it scales up as well
38
The idea is simple: A random ordering will result in very small contiguous
ordered blocks in either direction. Snake sort begins by identifying all those
blocks, and then merges them together. Each merge pass will halve the
It uses quite a bit of memory: a full copy of the original array, plus an index
array (to remember the block cutoffs) half the size of the original array.
The most interesting feature of snake sort is that the more ordered the array
2.7 COMPARISON
and "Worst" give the time complexity in each case, under the assumption
that the length of each key is constant, and that therefore all comparisons,
swaps, and other needed operations can proceed in constant time. "Memory"
denotes the amount of auxiliary storage needed beyond that used by the list
39
itself, under the same assumption. These are all comparison sorts. The run
notations like theta, omega, Big-O, small-o, etc. The memory and the run
Implemented in
Standard Template
Library (STL); can
In-place
Yes Merging be implemented as
Merge sort
a stable sort based
on stable in-place
merging
40
Name Best Average Worst Memory Stable Method Other notes
Partition-
Used
ing &
Introsort No in SGI STL implem
Select-
entations
ion
Depends;
worst
Merge sort Yes Merging
case
is
Finds all
Insertion the longest
Patience
— — No & increasing
sorting
Selection subsequences withi
n O(n log n)
Quicksort is usually
done in place with
O(log(n)) stack
space. Most
implementations
Partition- are unstable, as
Quicksort Depends
ing stable in-place
partitioning is more
complex. Naïve vari
ants use an O(n)
space array to
store the partition.
41
Name Best Average Worst Memory Stable Method Other notes
Depends
on gap
sequence;
Shell sort or No Insertion
best known
is
Remarkably
Slow sort — — — No Selection inefficient sorting
algorithm
An adaptive sort -
comparisons
Smoothsort No Selection when the data is
already sorted, and
0 swaps.
Strand sort Yes Selection
comparisons
Insertion
when the data is
Timsort Yes &
already sorted or
Merging
reverse sorted.
Tournament
— Selection
sort
The following table describes integer sorting algorithms and other sorting
algorithms that are not comparison sorts. As such, they are not limited by a
implementation. Many of them are based on the assumption that the key
size is large enough that all entries have unique key values, and hence that n
k
Name Best Average Worst Memory Stable n << 2 Notes
43
2.7.2 Non-Comparison Sorts
k
Name Best Average Worst Memory Stable n << 2 Notes
The following table describes some sorting algorithms that are impractical
specialized hardware.
44
2.7.3 Impractical Sorts
Bead
— N/A N/A — N/A No Requires specialized hardware
sort
Simple
pancake — No Yes Count is number of flips.
sort
45
Algorithms not yet compared above include:
Odd-even sort
Flash sort
Burst sort
Postman sort
Stooge sort
Sample sort
Bitonic sorter
46
CHAPTER THREE
This chapter discusses how the proposed application will be implemented by giving an
overview of the proposed application, describing the working operations, analysis of it and
the design.
3.0. INTRODUCTION
47
Worst-case O(n∙lg(n)) key comparisons.
There is no algorithm that has all these properties, and so the choice of
effective.
II. A good system must be user friendly and the user interface must be
IV. A good system design must be maintainable with a very simple and
self-explanatory documentation.
48
V. A good system design must be reliable, secured and put into
or abuse.
The Program is written in Visual Basic .NET (Visual Studio 2010, .NET
Framework 4.)
language that can be viewed as an evolution of the classic Visual Basic (VB),
49
3.5. PROGRAM ARCHITECTURE
The first class contains the various subroutines used in the program while
the module contains the actual sorting algorithm (insert sort) used in the
program.
The second class is nested in the first class because it’s a Private class.
There are 3 tabs in the application. Each tab solves a particular problem.
Tab 1: Basic Sorting: It allows the user to input a set of numbers and sorts it
and also removes duplicates. This process can also be automated in which
Tab 2: Sort Text File: This example, takes a text file, splits the contents,
sorts the resulting string alphabetically and rewrites it back to the text file.
50
Tab 3: Sort by Key Fields: This example sorts different objects by different
key fields.
51
CHAPTER FOUR
SYSTEM IMPLEMENTATION
This chapter takes a broad look at the working operations of the application, the chapter
exposes it to real life scenarios to confirm the performance, It starts by taking a look at the
The program is a very light program that requires very little processing
power and memory space to run. For a successful running of the program,
I. Operating System:
version.
52
o Linux or other variants like Ubuntu
The program is very light (about 100kb) and requires no installation. The
user simply clicks and runs it from the storage media on which it is saved.
It allows the user to input a set of numbers and sorts it and also removes
53
Figure 4-1: Tab 1: Basic Sorting
54
d) The number is then added to Listbox1
The user will go over these steps till he has input all the numbers he
wishes to sort.
2. After the inputs, the user clicks the Sort button and the add button is
program then copies all the items in listbox1 to an array and sorts the
array using the Insert sort algorithm. The resulting sorted array is then
copies to ListBox2
3. The user can remove duplicate items from the new sorted array by
into ListBox1 and sort them into ListBox2. To do this, the user
5. An input box is displayed prompting the user to input the range of the
dataset. If the range is higher than 6,400, the user is alerted that datasets
55
higher than that figure results in exponentially longer run time and
This example, takes a text file, splits the contents, sorts the resulting string
56
1. The file to be analyzed must be a text (.txt) file. Hence if the user
wants to sort the contents of a Word (.docx) or a Pfd (.pdf) file, the
user must copy the contents of the file onto a blank Notepad.
2. The user copies the file address into the text box supplied.
3. The student then selects the delimiter that separates each item in the
text file.
4. Once the “Open + Split” Button is clicked, the program first checks if
the file address specified in the text box exists. If it does, it then
5. If the text file path does not exist or is empty, the user is notified and
6. Once the input is valid (i.e. the file exists and is not empty), the
program copies the content of the text file and splits it using the
7. The output of the split, a string array, is then copied into the
ListBox.
8. The user clicks the “Sort” button to sort the contents of the
ListBox.
57
9. Once the ListBox is sorted, the user clicks on “Rewrite” button to
10. The Len box displays the number of characters in the text file while
the Num box displays the number of words in the text file.
The example simply shows that objects with several fields can be sorted by
The user selects the radio button by Name or by ID and the program sorts
58
Figure 4-3: Tab 3: Sort by Key Field
59
CHAPTER FIVE
5.1 CONCLUSION
5.2 RECOMMENDATION
This application and procedures therein can be further expanded and used
60
REFERENCES
Charles E., Rivest, Ronald L., Stein, Clifford (2009) [1990]. Introduction to
Algorithms (3rd ed.). MIT Press and McGraw-Hill. ISBN 0-262-03384-4
Insertion Sort & Shellsort, Andy Le, CS146 – Dr. Sin Min Lee, Spring 2004,
61
LaMarca, A.; Ladner, R. E. (1997). "The influence of caches on the
performance of sorting". Proc. 8th Ann. ACM-SIAM Symp. on Discrete
Algorithms (SODA97): 370–379
http://www.sorting-algorithms.com
WIKIPEDIA - http://en.wikipedia.org/wiki/Sorting_algorithm
http://en.wikipedia.org/wiki/Sorting
62
APPENDIX A
Humorous or ineffective
7. Bogosort
8. Stooge sort
Hybrid
9. Introsort: begin with quicksort and switch to heapsort when the
recursion depth exceeds a certain level
10. JSort
11. Spread sort
12. Timsort: adaptive algorithm derived from merge sort and insertion
sort. Used in Python 2.3 and up, and Java SE 7.
13. UnShuffle sort
Insertion sorts
14. Cycle sort: in-place with theoretically optimal number of writes
15. Insertion sort: determine where the current item belongs in the list of
sorted ones, and insert it there
16. Library sort
63
17. Patience sorting
18. Shell sort: an attempt to improve insertion sort
19. Tree sort (binary tree sort): build binary tree, then traverse it to
create sorted list
Merge sorts
20. Merge sort: sort the first and second half of the list separately, then
merge the sorted lists
21. Polyphase merge sort
22. Strand sort
Selection sorts
32. Cartesian Tree sort
33. Cycle sort
34. Heap sort: convert the list into a heap, keep removing the largest
element from the heap and adding it to the end of the list
35. Selection sort: pick the smallest of the remaining elements, add it to
the end of the sorted list
64
36. Smooth sort
37. Tournament sort
Concurrent sorts
38. Batch odd-even mergesort
39. Bitonic sorter
40. Pairwise sorting network
Other
41. Pancake sorting
42. Topological sort
Unknown class
43. Distribution sort
44. Jump sort
45. Samplesort
46. Shaker sort
47. Snake sort
65
APPENDIX B
Pseudocode Implementation of some Sorting Algorithms
function bucketSort(array, n) is
buckets ← new array of n empty lists
for i = 0 to (length(array)-1) do
insert array[i] into buckets[msbits(array[i], k)]
for i = 0 to n - 1 do
nextSort(buckets[i])
return the concatenation of buckets[0], ..., buckets[n-1]
66
(c) Counting Sort
67
(d) Merge Sort
function merge_sort(list m)
// if list size is 1, consider it sorted and return it
if length(m) <= 1
return m
// else list size is > 1, so split the list into two sublists
var list left, right
var integer middle = length(m) / 2
for each x in m up to middle
add x to left
for each x in m after or equal middle
add x to right
// recursively call merge_sort() to further split each sublist
// until sublist size is 1
left = merge_sort(left)
right = merge_sort(right)
// merge the sublists returned from prior calls to merge_sort()
// and return the resulting merged sublist
return merge(left, right)
68
APPENDIX C
Some Sorting Algorithms in Visual Basic
= = = = = = = = = = = = = = = = = = = = = = = =
(A) insert sort
= = = = = = = = = = = = = = = = = = = = = = = =
'sort A[Lb..Ub]
For i = Lb + 1 To Ub
t = A(i)
69
= = = = = = = = = = = = = = = = = = = = = = = =
(B) QSort
= = = = = = = = = = = = = = = = = = = = = = = =
lbStack(0) = Lb
ubStack(0) = Ub
sp = 0
Do While sp >= 0
lbx = lbStack(sp)
ubx = ubStack(sp)
70
' exchange lbx, p
t = A(lbx)
A(lbx) = A(p)
A(p) = t
Do While j >= i
If A(j) <= A(lbx) Then Exit Do
j = j - 1
Loop
' exchange i, j
t = A(i)
A(i) = A(j)
A(j) = t
j = j - 1
i = i + 1
Loop
71
m = j
= = = = = = = = = = = = = = = = = = = = = = = =
(C) Quick Sort
= = = = = = = = = = = = = = = = = = = = = = = =
Do While Lb < Ub
72
' quickly sort short lists
If (Ub - Lb <= 12) Then
Call InsertSort(A, Lb, Ub)
Exit Sub
End If
---------
73
pivot = A(p)
A(p) = A(Lb)
= = = = = = = = = = = = = = = = = = = = = = = =
(D) Shell Sort
= = = = = = = = = = = = = = = = = = = = = = = =
74
Dim n As Long
Dim h As Long
Dim i As Long
Dim j As Long
Dim s As Long
Dim t As Variant
Dim seq(28) As Long
s = ShellSeq(seq, Ub - Lb + 1)
Do While s >= 0
Dim p1 As Long
Dim p2 As Long
75
Dim p3 As Long
Dim s As Long
p1 = 1
p2 = 1
p3 = 1
s = -1
Do
s = s + 1
If s Mod 2 Then
h(s) = 8 * p1 - 6 * p2 + 1
Else
h(s) = 9 * p1 - 9 * p3 + 1
p2 = 2 * p2
p3 = 2 * p3
End If
p1 = 2 * p1
Loop While 3 * h(s) < n
If s > 0 Then s = s - 1
ShellSeq = s
End Function
76
APPENDIX D
PROGRAM SOURCE CODE
MICROSOFT VISUAL STUDIO 2010 ULTIMATE
.NET FRAMEWORK 4 BETA 2
Imports System.IO
Imports Microsoft.VisualBasic.FileSystem
Imports System.Windows.Forms.KeyEventArgs
For nu = 0 To elem
array1(nu) = aa.Items.Item(nu)
Next
For nu = 0 To elem
bb.Items.Add(array1(nu))
Next
''
End Sub
77
m_Items(0) = New CustomerInfo("Archer", 4)
m_Items(1) = New CustomerInfo("Beck", 7)
m_Items(2) = New CustomerInfo("Cantu", 2)
m_Items(3) = New CustomerInfo("Deevers", 1)
m_Items(4) = New CustomerInfo("Edwards", 9)
m_Items(5) = New CustomerInfo("Finnagan", 3)
m_Items(6) = New CustomerInfo("Guy", 5)
m_Items(7) = New CustomerInfo("Hennesey", 8)
m_Items(8) = New CustomerInfo("Jacquinth", 6)
m_Items(9) = New CustomerInfo("Irving", 10)
'' Uncomment to test duplicate objects.
'm_Items(6) = New CustomerInfo("Finnagan", 3)
'm_Items(7) = New CustomerInfo("Edwards", 9)
'm_Items(8) = New CustomerInfo("Finnagan", 3)
'm_Items(9) = New CustomerInfo("Deevers", 1)
txt.Focus()
End Sub
#End Region
78
End Sub
Sub add()
If addBtn.Enabled = True Then
Dim item As Single = Val(txt.Text)
If item <= 0 Then
txt.Clear()
Exit Sub
End If
ListBox1.Items.Add(item)
txt.Clear()
End If
txt.Focus()
End Sub
With ListBox2.Items
For i = 1 To 7
Dim oOK As Integer = .Count - 1
Dim c1 As Integer = 0
79
.RemoveAt(c1)
oOK -= 1
End If
c1 += 1
End While
Next
End With
End Sub
sort(ListBox1, ListBox2)
addBtn.Enabled = False
End Sub
ListBox1.Items.Clear()
ListBox2.Items.Clear()
Dim tim = Timer
80
For autoGen = 1 To auto
ListBox1.Items.Add(Int((1000 * Rnd()) + 1))
Next
sort(ListBox1, ListBox2)
MsgBox("Dataset of " & auto & " items was sorted in " & (Timer - tim)
& " seconds!", MsgBoxStyle.Information, "TIME")
End Sub
#End Region
Try
content = FileIO.FileSystem.ReadAllText(dir.Text)
Catch
MsgBox("check your file dir")
dir.Focus()
Exit Sub
End Try
81
split = content.Split(New [Char]() {" "c})
Case "Comma"
split = content.Split(New [Char]() {","c})
Case "Underscore"
split = content.Split(New [Char]() {"_"c})
Case "@"
split = content.Split(New [Char]() {"@"c})
Case "/"
split = content.Split(New [Char]() {"/"c})
Case "\"
split = content.Split(New [Char]() {"\"c})
Case "#"
split = content.Split(New [Char]() {"#"c})
Case "$"
split = content.Split(New [Char]() {"$"c})
Case ":"
split = content.Split(New [Char]() {":"c})
Case "&"
split = content.Split(New [Char]() {"&"c})
Case "*"
split = content.Split(New [Char]() {"*"c})
Case "-"
split = content.Split(New [Char]() {"-"c})
Case "+"
split = content.Split(New [Char]() {"+"c})
Case "="
split = content.Split(New [Char]() {"="c})
Case Else
split = content.Split(New [Char]() {" "c, ","c, ":"c, "/"c,
CChar(vbTab), CChar(vbNewLine)})
End Select
ListBox3.Items.Clear()
End Sub
82
End Sub
content = FileIO.FileSystem.ReadAllText(dir.Text)
FileIO.FileSystem.WriteAllText(dir.Text, "", False)
Try
For i = 0 To ListBox3.Items.Count - 1
a = ListBox3.Items.Item(i) & vbNewLine
FileIO.FileSystem.WriteAllText(dir.Text, a, True)
Next
Catch ex As Exception
FileIO.FileSystem.WriteAllText(dir.Text, content, False)
MsgBox("an error occured")
End Try
End Sub
#End Region
83
Select Case CompareType
Case CompareTypes.ById
Return x_cust.ID.CompareTo(y_cust.ID)
Case CompareTypes.ByName
Return x_cust.Name.CompareTo(y_cust.Name)
End Select
End Function
End Class
#End Region
End Class
Module all
84
Dim t As Object
Dim i As Long
Dim j As Long
End Module
85